repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/RectangleOnHex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangle shaped board with a hexagonal tiling.
*
* @author cambolbro
*/
@Hide
public class RectangleOnHex extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public RectangleOnHex
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
final int rows = dimA.eval();
final int cols = (dimB != null) ? dimB.eval() : rows;
this.basis = BasisType.Hexagonal;
this.shape = (rows == cols) ? ShapeType.Square : ShapeType.Rectangle;
this.dim = new int[]{ rows, cols };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[1];
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols + rows; c++)
{
if (c < (r + 1) / 2 || c >= cols + r / 2)
continue;
final Point2D ptRef = Hex.xy(r, c);
for (int n = 0; n < 6; n++)
{
final double x = ptRef.getX() + Hex.ref[n][0];
final double y = ptRef.getY() + Hex.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.HexTiling.id(), true);
concepts.set(Concept.RectangleShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,207 | 23.676923 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/StarOnHex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a six-pointed star board on a hexagonal grid.
*
* @author cambolbro
*/
@Hide
public class StarOnHex extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dim The dimension.
*/
public StarOnHex(final DimFunction dim)
{
this.basis = BasisType.Hexagonal;
this.shape = ShapeType.Star;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int d = dim[0];
final int rows = 4 * dim[0] + 1;
final int cols = 4 * dim[0] + 1;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r < d)
{
if (c < d || c - r > d)
continue;
}
else if (r <= 2 * d)
{
if (r - c > d || c >= cols - d)
continue;
}
else if (r <= 3 * d)
{
if (c < d || c - r > d)
continue;
}
else
{
if (c > 3 * d || r - c > d)
continue;
}
final Point2D ptRef = Hex.xy(r, c);
for (int n = 0; n < 6; n++)
{
final double x = ptRef.getX() + Hex.ref[n][0];
final double y = ptRef.getY() + Hex.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.HexTiling.id(), true);
concepts.set(Concept.StarShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,234 | 22.107143 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/TriangleOnHex.java | package game.functions.graph.generators.basis.hex;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangle shaped board with a hexagonal tiling.
*
* @author cambolbro
*/
@Hide
public class TriangleOnHex extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dim The dimension.
*/
public TriangleOnHex(final DimFunction dim)
{
this.basis = BasisType.Hexagonal;
this.shape = ShapeType.Triangle;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[0];
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r > c)
continue;
final Point2D ptRef = Hex.xy(r, c);
for (int n = 0; n < 6; n++)
{
final double x = ptRef.getX() + Hex.ref[n][0];
final double y = ptRef.getY() + Hex.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.HexTiling.id(), true);
concepts.set(Concept.TriangleShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,928 | 23.408333 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/hex/package-info.java | /**
* This section contains the boards based on a hexagonal tiling.
*
*/
package game.functions.graph.generators.basis.hex;
| 128 | 20.5 | 64 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/mesh/CustomOnMesh.java | package game.functions.graph.generators.basis.mesh;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
import java.util.Random;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.GraphElement;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a graph from a triangular mesh.
*
* @author cambolbro
*/
@Hide
public class CustomOnMesh extends Basis
{
private static final long serialVersionUID = 1L;
private final Integer numVertices;
private final Polygon polygon = new Polygon();
private final List<Point2D> points;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Mesh.
*
* @param numVertices
* @param polygon
* @param points
*/
public CustomOnMesh
(
final DimFunction numVertices,
final Polygon polygon,
final List<Point2D> points
)
{
this.basis = BasisType.Mesh;
this.shape = ShapeType.Custom;
this.numVertices = Integer.valueOf(numVertices.eval());
this.points = points;
this.polygon.setFrom(polygon);
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final Graph graph = new Graph();
if (numVertices == null)
{
// Just use the points directly as vertices
for (final Point2D pt : points)
insertVertex(graph, pt);
}
else
{
// Fill the shape with N randomly generated vertices
final Random rng = new Random();
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
for (int n = 0; n < numVertices.intValue(); n++)
{
int iterations = 0;
Point2D pt;
do
{
if (++iterations > 1000)
throw new RuntimeException("Couldn't place point in mesh shape.");
final double x = bounds.getMinX() + rng.nextDouble() * bounds.getWidth();
final double y = bounds.getMinY() + rng.nextDouble() * bounds.getHeight();
pt = new Point2D.Double(x, y);
} while (!polygon.contains(pt));
insertVertex(graph, pt);
}
}
graph.makeFaces(true);
graph.setBasisAndShape(basis, shape);
//graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
static void insertVertex(final Graph graph, final Point2D pt)
{
final List<? extends GraphElement> vertices = graph.elements(SiteType.Vertex);
if (vertices.isEmpty())
{
// Add first vertex
graph.addVertex(pt);
return;
}
else if (vertices.size() == 1)
{
// Add second vertex
graph.addVertex(pt);
graph.findOrAddEdge(0, 1);
return;
}
else if (vertices.size() == 2)
{
// Add third vertex
graph.addVertex(pt);
graph.findOrAddEdge(0, 2);
graph.findOrAddEdge(1, 2);
return;
}
// Add vertex in inscribed triangle, if any
for (int i = 0; i < vertices.size(); i++)
{
final Vertex vertexI = (Vertex)vertices.get(i);
for (int j = i + 1; j < vertices.size(); j++)
{
if (i == j)
continue;
final Vertex vertexJ = (Vertex)vertices.get(j);
for (int k = j + 1; k < vertices.size(); k++)
{
if (i == k || j == k)
continue;
final Vertex vertexK = (Vertex)vertices.get(k);
if (MathRoutines.pointInTriangle(pt, vertexI.pt2D(), vertexJ.pt2D(), vertexK.pt2D()))
{
// Point lies within the triangle formed by I, J, K
insertVertex(graph, pt, vertexI, vertexJ, vertexK);
return;
}
}
}
}
// Point must be outside current mesh, add to two nearest vertices
// **
// ** TODO: This could allow edge crossings.
// ** Do not include vertices that would cause an edge crossing.
// **
double bestDistance = 1000000;
double nextBestDistance = 1000000;
GraphElement bestVertex = null;
GraphElement nextBestVertex = null;
for (final GraphElement vertex : vertices)
{
final double dist = MathRoutines.distance(pt, vertex.pt2D());
// if (dist < bestDistance || dist < nextBestDistance)
// {
// if (would cause edge crossing)
// continue;
// }
if (dist < bestDistance)
{
nextBestDistance = bestDistance;
nextBestVertex = bestVertex;
bestDistance = dist;
bestVertex = vertex;
}
else if (dist < nextBestDistance)
{
nextBestDistance = dist;
nextBestVertex = vertex;
}
}
final Vertex vertex = graph.addVertex(pt);
graph.findOrAddEdge(vertex.id(), bestVertex.id());
graph.findOrAddEdge(vertex.id(), nextBestVertex.id());
}
//-------------------------------------------------------------------------
static void insertVertex
(
final Graph graph, final Point2D pt,
final Vertex vertexI, final Vertex vertexJ, final Vertex vertexK
)
{
final Vertex vertex = graph.addVertex(pt);
// if near to existing edge, delete edge but relink affected vertex
graph.findOrAddEdge(vertex.id(), vertexI.id());
graph.findOrAddEdge(vertex.id(), vertexJ.id());
graph.findOrAddEdge(vertex.id(), vertexK.id());
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 6,272 | 24.5 | 102 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/mesh/Mesh.java | package game.functions.graph.generators.basis.mesh;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Creates a graph based on a random spread of points within a given shape.
*
* @author cambolbro
*
* The mesh is based on a Delaunay triangulation of the points.
*/
@SuppressWarnings("javadoc")
@Hide
public class Mesh extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param numVertices Number of vertices to generate.
* @param poly Outline shape to fill [square].
*
* @example (mesh 50)
* @example (mesh 64 (poly { {0 0} {0 3} {2 2} {2 0} } ))
*/
public static GraphFunction construct
(
final DimFunction numVertices,
@Opt final Poly poly
)
{
return new CustomOnMesh
(
numVertices,
(poly == null ? new Polygon(4) : poly.polygon()),
null
);
}
/**
* @param points Actual (x,y) point positions to use.
*
* @example (mesh { {0 0} {0 1} {0.5 0.5} {1 1} {1 0} } )
*/
public static GraphFunction construct
(
final Float[][] points
)
{
final List<Point2D> pointsList = new ArrayList<Point2D>();
for (final Float[] xy : points)
{
if (xy.length < 2)
{
System.out.println("** Mesh: Points should have two values.");
continue;
}
pointsList.add(new Point2D.Double(xy[0].floatValue(), xy[1].floatValue()));
}
return new CustomOnMesh(null, null, pointsList);
}
//-------------------------------------------------------------------------
// /**
// * @param poly Vertex positions.
// *
// * @example (mesh { {0 0} {0 1} {0.5 0.5} {1 1} {1 0} } )
// */
// public static GraphFunction construct
// (
// final Float[][] points
// )
// {
// return new CustomOnMesh(null, points);
// }
//-------------------------------------------------------------------------
private Mesh()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Mesh
return null;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 2,980 | 22.108527 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/mesh/package-info.java | /**
* This section contains the boards described by a mesh of points.
*
*/
package game.functions.graph.generators.basis.mesh;
| 131 | 21 | 66 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/quadhex/Quadhex.java | package game.functions.graph.generators.basis.quadhex;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a ``quadhex'' board.
*
* @author cambolbro
*
* @remarks The quadhex board is a hexagon tessellated by quadrilaterals,
* as used for the Three Player Chess board.
* The number of cells per side will be twice the number of layers.
*/
public class Quadhex extends Basis
{
private static final long serialVersionUID = 1L;
private final boolean thirds;
//-------------------------------------------------------------------------
/**
* @param layers Number of layers.
* @param thirds Whether to split the board into three-subsections [False].
*
* @example (quadhex 4)
*/
public Quadhex
(
final DimFunction layers,
@Opt @Name final Boolean thirds
)
{
this.basis = BasisType.QuadHex;
this.shape = ShapeType.Hexagon;
this.dim = new int[] { layers.eval() };
this.thirds = (thirds == null) ? false : thirds.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final Graph graph = new Graph();
final int layers = dim[0];
if (thirds)
threeUniformSections(graph, layers);
else
sixUniformSections(graph, layers);
graph.makeFaces(true);
graph.setBasisAndShape(basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@SuppressWarnings("static-method")
void sixUniformSections(final Graph graph, final int layers)
{
// B----C
// | \
// | \
// | D
// | / .
// | / .
// | / .
// |/. . . . . E
// A
final Point2D ptA = new Point2D.Double(0, 0);
final Point2D ptB = new Point2D.Double(0, layers * Math.sqrt(3) / 2);
final Point2D ptC = new Point2D.Double(layers / 2.0, layers * Math.sqrt(3) / 2);
final Point2D ptE = new Point2D.Double(layers, 0);
final Point2D ptD = new Point2D.Double
(
(ptC.getX() + ptE.getX()) / 2,
(ptC.getY() + ptE.getY()) / 2
);
for (int rotn = 0; rotn < 6; rotn++)
{
final double theta = rotn * Math.PI / 3;
for (int row = 0; row < layers; row++)
{
final double r0 = row / (double)layers;
final double r1 = (row + 1) / (double)layers;
final Point2D ptAD0 = MathRoutines.rotate(theta, MathRoutines.lerp(r0, ptA, ptD));
final Point2D ptAD1 = MathRoutines.rotate(theta, MathRoutines.lerp(r1, ptA, ptD));
final Point2D ptBC0 = MathRoutines.rotate(theta, MathRoutines.lerp(r0, ptB, ptC));
final Point2D ptBC1 = MathRoutines.rotate(theta, MathRoutines.lerp(r1, ptB, ptC));
for (int col = 0; col < layers; col++)
{
final double c0 = col / (double)layers;
final double c1 = (col + 1) / (double)layers;
final Point2D ptAB0 = MathRoutines.lerp(c0, ptAD0, ptBC0);
final Point2D ptAB1 = MathRoutines.lerp(c1, ptAD0, ptBC0);
final Point2D ptDC1 = MathRoutines.lerp(c1, ptAD1, ptBC1);
final Vertex vertexA = graph.findOrAddVertex(ptAB0);
final Vertex vertexB = graph.findOrAddVertex(ptAB1);
final Vertex vertexC = graph.findOrAddVertex(ptDC1);
graph.findOrAddEdge(vertexA, vertexB);
graph.findOrAddEdge(vertexB, vertexC);
if (row == layers - 1)
{
final Point2D ptDC0 = MathRoutines.lerp(c0, ptAD1, ptBC1);
final Vertex vertexD = graph.findOrAddVertex(ptDC0);
graph.findOrAddEdge(vertexC, vertexD);
}
}
}
}
}
//-------------------------------------------------------------------------
@SuppressWarnings("static-method")
void threeUniformSections(final Graph graph, final int layers)
{
//final double tolerance = 0.001;
// C . . . . . . . O . . . . . . . D
// . .
// . __F__ .
// . __–– | ––__ .
// . __–– | ––__ .
// G | H
// \ | /
// \ | /
// A–––––––E–––––––B
final double L32 = layers * Math.sqrt(3) / 2;
final Point2D ptO = new Point2D.Double(0, 0);
final Point2D ptA = new Point2D.Double(-layers/2.0, -L32);
//final Point2D ptB = new Point2D.Double(layers/2.0, -L32);
final Point2D ptC = new Point2D.Double(-layers, 0);
//final Point2D ptD = new Point2D.Double(layers, 0);
final Point2D ptE = new Point2D.Double(0, -L32);
final double ratio = layers / (layers + 0.5);
final Point2D ptF = MathRoutines.lerp(ratio, ptE, ptO);
final Point2D ptG = MathRoutines.lerp(ratio/2, ptA, ptC);
//final Point2D ptH = MathRoutines.lerp(ratio/2, ptB, ptD);
final Graph section = new Graph();
for (int row = 0; row < layers; row++)
{
final double r0 = row / (double)layers;
final double r1 = (row + 1) / (double)layers;
final Point2D ptAE0 = MathRoutines.lerp(r0, ptA, ptE);
final Point2D ptAE1 = MathRoutines.lerp(r1, ptA, ptE);
final Point2D ptGF0 = MathRoutines.lerp(r0, ptG, ptF);
final Point2D ptGF1 = MathRoutines.lerp(r1, ptG, ptF);
for (int col = 0; col < layers; col++)
{
final double c0 = col / (double)layers;
final double c1 = (col + 1) / (double)layers;
final Point2D ptAG0 = MathRoutines.lerp(c0, ptAE0, ptGF0);
final Point2D ptAG1 = MathRoutines.lerp(c1, ptAE0, ptGF0);
final Point2D ptEF0 = MathRoutines.lerp(c0, ptAE1, ptGF1);
final Point2D ptEF1 = MathRoutines.lerp(c1, ptAE1, ptGF1);
final Vertex vertexA = section.findOrAddVertex(ptAG0);
final Vertex vertexB = section.findOrAddVertex(ptAG1);
final Vertex vertexC = section.findOrAddVertex(ptEF0);
final Vertex vertexD = section.findOrAddVertex(ptEF1);
section.findOrAddEdge(vertexA, vertexB);
section.findOrAddEdge(vertexC, vertexD);
section.findOrAddEdge(vertexA, vertexC);
section.findOrAddEdge(vertexB, vertexD);
final Point2D ptAA = new Point2D.Double(-ptAG0.getX(), ptAG0.getY());
final Point2D ptBB = new Point2D.Double(-ptAG1.getX(), ptAG1.getY());
final Point2D ptCC = new Point2D.Double(-ptEF0.getX(), ptEF0.getY());
final Point2D ptDD = new Point2D.Double(-ptEF1.getX(), ptEF1.getY());
final Vertex vertexAA = section.findOrAddVertex(ptAA);
final Vertex vertexBB = section.findOrAddVertex(ptBB);
final Vertex vertexCC = section.findOrAddVertex(ptCC);
final Vertex vertexDD = section.findOrAddVertex(ptDD);
section.findOrAddEdge(vertexAA, vertexBB);
section.findOrAddEdge(vertexCC, vertexDD);
section.findOrAddEdge(vertexAA, vertexCC);
section.findOrAddEdge(vertexBB, vertexDD);
}
}
// Duplicate three sections, rotated
final int verticesPerSection = section.vertices().size();
final double theta = 2 * Math.PI / 3;
final Vertex[][] save = new Vertex[3][3];
for (int rotn = 0; rotn < 3; rotn++)
{
for (final Vertex vertex : section.vertices())
graph.addVertex(vertex.pt2D().getX(), vertex.pt2D().getY());
for (final Edge edge : section.edges())
graph.addEdge
(
edge.vertexA().id() + rotn * verticesPerSection,
edge.vertexB().id() + rotn * verticesPerSection
);
// Perform rotation
for (final Vertex vertex : section.vertices())
{
// x′ = x.cosθ − y.sinθ
// y′ = y.cosθ + x.sinθ
final double dx = vertex.pt().x();
final double dy = vertex.pt().y();
final double xx = dx * Math.cos(theta) - dy * Math.sin(theta);
final double yy = dy * Math.cos(theta) + dx * Math.sin(theta);
vertex.pt().set(xx, yy);
}
save[0][rotn] = graph.vertices().get(rotn * verticesPerSection + 4 * layers);
save[1][rotn] = graph.vertices().get(rotn * verticesPerSection + 4 * layers + 2);
save[2][rotn] = graph.vertices().get(rotn * verticesPerSection + layers * (2 * layers + 3));
}
// Make middle triangle
graph.findOrAddEdge(save[2][0], save[2][1]);
graph.findOrAddEdge(save[2][1], save[2][2]);
graph.findOrAddEdge(save[2][2], save[2][0]);
// Join corners of sections
graph.findOrAddEdge(save[1][0], save[0][1]);
graph.findOrAddEdge(save[1][1], save[0][2]);
graph.findOrAddEdge(save[1][2], save[0][0]);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.QuadHexTiling.id(), true);
concepts.set(Concept.HexShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 9,455 | 29.701299 | 96 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/quadhex/package-info.java | /**
* This section contains the boards based on the ``quadhex'' tiling.
* This is a hexagon tessellated by quadrilaterals,
* as used for the Three Player Chess board.
*/
package game.functions.graph.generators.basis.quadhex;
| 230 | 32 | 68 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/CustomOnSquare.java | package game.functions.graph.generators.basis.square;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a rectangular board.
*
* @author cambolbro
*
*/
@Hide
public class CustomOnSquare extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
private final DiagonalsType diagonals;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Square.
*
* @param polygon The polygons.
* @param diagonals The diagonal type.
*/
public CustomOnSquare
(
final Polygon polygon,
final DiagonalsType diagonals
)
{
this.basis = BasisType.Square;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
this.diagonals = diagonals;
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The sides.
* @param diagonals The diagonal type.
*/
public CustomOnSquare
(
final DimFunction[] sides,
final DiagonalsType diagonals
)
{
this.basis = BasisType.Square;
this.shape = ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
this.diagonals = diagonals;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (polygon.isEmpty() && !sides.isEmpty())
polygon.fromSides(sides, Square.steps);
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
final int fromCol = (int)bounds.getMinX() - 2;
final int fromRow = (int)bounds.getMinY() - 2;
final int toCol = (int)bounds.getMaxX() + 2;
final int toRow = (int)bounds.getMaxY() + 2;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = fromRow; row <= toRow; row++)
for (int col = fromCol; col <= toCol; col++)
{
final double x = col;
final double y = row;
if (polygon.contains(x, y))
vertexList.add(new double[] { x, y });
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
Square.handleDiagonals(graph, fromRow, toRow, fromCol, toCol, diagonals); //, 0.0001);
graph.makeFaces(false);
graph.setBasisAndShape(basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// ...
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if(diagonals == null)
concepts.set(Concept.SquareTiling.id(), true);
else if(diagonals.equals(DiagonalsType.Alternating))
concepts.set(Concept.AlquerqueTiling.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,666 | 22.811688 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/DiagonalsType.java | package game.functions.graph.generators.basis.square;
/**
* Defines how to handle diagonal relations on the Square tiling.
*
* @author cambolbro
*/
public enum DiagonalsType //implements GraphicsItem
{
/** Diagonal connections (not edges) between opposite corners. */
Implied,
/** Solid edges between opposite diagonals, which split the square into four triangles. */
Solid,
/** Solid edges between opposite diagonals, but do not split the square into four triangles. */
SolidNoSplit,
/** Every second diagonal is a solid edge, as per Alquerque boards. */
Alternating,
/** Concentric diagonal rings from the centre. */
Concentric,
/** Diagonals radiating from the centre. */
Radiating,
}
| 715 | 24.571429 | 96 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/DiamondOnSquare.java | package game.functions.graph.generators.basis.square;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a diamond shaped board on a square tiling.
*
* @author cambolbro
*
*/
@Hide
public class DiamondOnSquare extends Basis
{
private static final long serialVersionUID = 1L;
private final DiagonalsType diagonals;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Rectangle.
*
* @param dim The dimension.
* @param diagonals The diagonal type.
*/
public DiamondOnSquare
(
final DimFunction dim,
final DiagonalsType diagonals
)
{
this.basis = BasisType.Square;
this.shape = ShapeType.Diamond;
this.dim = new int[] { dim.eval() };
this.diagonals = diagonals;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Always use dim as dim is the same whether playing on vertices or cells
final int d = dim[0];
final int rows = 2 * d;
final int cols = 2 * d;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r + c < d-1 || c - r > d || r - c > d || r + c >= 3 * d)
continue;
vertexList.add(new double[] { c, r });
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
Square.handleDiagonals(graph, 0, rows, 0, cols, diagonals); //, 0.0001);
graph.makeFaces(false);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if (diagonals == null)
concepts.set(Concept.SquareTiling.id(), true);
else if (diagonals.equals(DiagonalsType.Alternating))
concepts.set(Concept.AlquerqueTiling.id(), true);
concepts.set(Concept.DiamondShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,820 | 22.705882 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/RectangleOnSquare.java | package game.functions.graph.generators.basis.square;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a rectangular board on a square grid.
*
* @author cambolbro
*/
@Hide
public class RectangleOnSquare extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final DiagonalsType diagonals;
private final boolean pyramidal;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for the Square tiling.
*
* @param rows The number of rows.
* @param columns The number of columns.
* @param diagonals The type of the diagonals.
* @param pyramidal True if this is a pyramidal rectangle.
*/
public RectangleOnSquare
(
final DimFunction rows,
final DimFunction columns,
final DiagonalsType diagonals,
final Boolean pyramidal
)
{
this.basis = BasisType.Square;
this.shape = (columns == null) ? ShapeType.Square : ShapeType.Rectangle;
this.diagonals = diagonals;
this.pyramidal = (pyramidal == null) ? false : pyramidal.booleanValue();
this.dim = new int[] { rows.eval(), (columns == null) ? rows.eval() : columns.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final Graph graph = new Graph();
// Add 1 if playing on the cells, as the number of cells in each
// direction is 1 less than the number of vertices.
final int rows = dim[0] + (siteType == SiteType.Cell ? 1 : 0);
final int cols = dim[1] + (siteType == SiteType.Cell ? 1 : 0);
// Create vertices
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
final Point2D pt = new Point2D.Double(col, row);
graph.addVertex(pt);
}
// Create edges
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
final Vertex vertexA = graph.findVertex(col, row);
for (int dirn = 0; dirn < Square.steps.length / 2; dirn++)
{
final int rr = row + Square.steps[dirn][0];
final int cc = col + Square.steps[dirn][1];
if (rr < 0 || rr >= rows || cc < 0 || cc >= cols)
continue;
final Vertex vertexB = graph.findVertex(cc, rr);
if (vertexA != null && vertexB != null)
graph.findOrAddEdge(vertexA, vertexB);
}
}
if (pyramidal)
{
// Equilateral square pyramid (all sides of unit length)
final double dz = 1.0 / Math.sqrt(2);
// Create vertices and edges for higher layers
final int layers = rows;
for (int layer = 1; layer < layers; layer++)
{
final double offX = layer * 0.5;
final double offY = layer * 0.5;
final double offZ = layer * dz;
// Create vertices for this layer
for (int row = 0; row < rows - layer; row++)
for (int col = 0; col < cols - layer; col++)
{
// Create this pyramidal vertex
final double x = offX + col;
final double y = offY + row;
final double z = offZ;
graph.findOrAddVertex(x, y, z);
}
}
// Add pyramidal edges
graph.makeEdges();
//graph.reorder();
}
Square.handleDiagonals(graph, 0, rows, 0, cols, diagonals);
//if (siteType == SiteType.Cell)
graph.makeFaces(false);
graph.setBasisAndShape(basis, shape);
graph.reorder();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
if (diagonals == null)
concepts.set(Concept.SquareTiling.id(), true);
else if (diagonals.equals(DiagonalsType.Alternating))
concepts.set(Concept.AlquerqueTiling.id(), true);
if (dim[0] == dim[1])
{
if(pyramidal)
concepts.set(Concept.SquarePyramidalShape.id(), true);
else
concepts.set(Concept.SquareShape.id(), true);
}
else
{
if(pyramidal)
concepts.set(Concept.RectanglePyramidalShape.id(), true);
else
concepts.set(Concept.RectangleShape.id(), true);
}
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,033 | 24.683673 | 90 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/Square.java | package game.functions.graph.generators.basis.square;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.dim.math.Add;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import game.util.graph.Vertex;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on a square tiling.
*
* @author cambolbro
*/
public class Square extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The steps.
*/
public static final int[][] steps = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
/**
* The diagonal steps.
*/
public static final int[][] diagonalSteps = { { 1, 1 }, { 1,-1 } };
//-------------------------------------------------------------------------
/**
* For defining a square tiling with the dimension.
*
* @param shape Board shape [Square].
* @param dim Board dimension; cells or vertices per side.
* @param diagonals How to handle diagonals between opposite corners [Implied].
* @param pyramidal Whether this board allows a square pyramidal stacking.
*
* @example (square Diamond 4)
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Opt final SquareShapeType shape,
final DimFunction dim,
@Opt @Or @Name final DiagonalsType diagonals,
@Opt @Or @Name final Boolean pyramidal
)
{
int numNonNull = 0;
if (diagonals != null)
numNonNull++;
if (pyramidal != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Only one of 'diagonals' and 'pyramidal' can be true.");
final SquareShapeType st = (shape == null) ? SquareShapeType.Square : shape;
switch (st)
{
case Square:
return new RectangleOnSquare(dim, dim, diagonals, pyramidal);
case Limping:
final DimFunction dimAplus1 = new Add(dim, new DimConstant(1));
return new RectangleOnSquare(dim, dimAplus1, diagonals, pyramidal);
case Diamond:
return new DiamondOnSquare(dim, diagonals);
//$CASES-OMITTED$
default:
throw new IllegalArgumentException("Shape " + st + " not supported for square tiling.");
}
}
/**
* For defining a square tiling with a polygon or the number of sides.
*
* @param poly Points defining the board shape.
* @param sides Length of consecutive sides of outline shape.
* @param diagonals How to handle diagonals between opposite corners [Implied].
*
* @example (square (poly { {1 2} {1 6} {3 6} {3 4} {4 4} {4 2} }))
* @example (square { 4 3 -1 2 3 })
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Or final Poly poly,
@Or final DimFunction[] sides,
@Opt @Name final DiagonalsType diagonals
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
if (poly != null)
return new CustomOnSquare(poly.polygon(), diagonals);
else
return new CustomOnSquare(sides, diagonals);
}
//-------------------------------------------------------------------------
private Square()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Square
return null;
}
//-------------------------------------------------------------------------
/**
* @param graph The graph.
* @param fromRow The origin row.
* @param toRow The target row.
* @param fromCol The origin column.
* @param toCol The target column.
* @param diagonals The type of diagonal.
*/
public static void handleDiagonals
(
final Graph graph,
final int fromRow, final int toRow, final int fromCol, final int toCol,
final DiagonalsType diagonals
)
{
if (diagonals == null)
return; // no diagonals: do nothing
if (diagonals == DiagonalsType.Alternating)
{
// Add diagonal edges to alternating cells
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
// Add diagonals from this vertex
final Vertex vertexA = graph.findVertex(c, r);
final Vertex vertexB = graph.findVertex(c, r+1);
final Vertex vertexC = graph.findVertex(c+1, r+1);
final Vertex vertexD = graph.findVertex(c+1, r);
if (vertexA == null || vertexB == null || vertexC == null || vertexD == null)
continue;
if ((r + c) % 2 == 0)
graph.findOrAddEdge(vertexA, vertexC);
else
graph.findOrAddEdge(vertexB, vertexD);
}
}
else if (diagonals == DiagonalsType.Solid)
{
// Add diagonal edges to all cells
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
// Add central vertex and edges to corner vertices
final Vertex vertexA = graph.findVertex(c, r);
final Vertex vertexB = graph.findVertex(c, r+1);
final Vertex vertexC = graph.findVertex(c+1, r+1);
final Vertex vertexD = graph.findVertex(c+1, r);
if (vertexA == null || vertexB == null || vertexC == null || vertexD == null)
continue;
final Vertex vertexX = graph.findOrAddVertex(c + 0.5, r + 0.5);
if (vertexX == null)
continue;
graph.findOrAddEdge(vertexA, vertexX);
graph.findOrAddEdge(vertexB, vertexX);
graph.findOrAddEdge(vertexC, vertexX);
graph.findOrAddEdge(vertexD, vertexX);
}
}
else if (diagonals == DiagonalsType.SolidNoSplit)
{
// Add diagonal edges to all cells
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
// Add central vertex and edges to corner vertices
final Vertex vertexA = graph.findVertex(c, r);
final Vertex vertexB = graph.findVertex(c, r+1);
final Vertex vertexC = graph.findVertex(c+1, r+1);
final Vertex vertexD = graph.findVertex(c+1, r);
if (vertexA == null || vertexB == null || vertexC == null || vertexD == null)
continue;
graph.findOrAddEdge(vertexA, vertexC);
graph.findOrAddEdge(vertexB, vertexD);
}
}
else if (diagonals == DiagonalsType.Concentric)
{
// Add diagonal edges to concentric squares around centre
final int midRow = (toRow + fromRow) / 2;
final int midCol = (toCol + fromCol) / 2;
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
// Add diagonals from this vertex
final Vertex vertexA = graph.findVertex(c, r);
final Vertex vertexB = graph.findVertex(c, r+1);
final Vertex vertexC = graph.findVertex(c+1, r+1);
final Vertex vertexD = graph.findVertex(c+1, r);
if (vertexA == null || vertexB == null || vertexC == null || vertexD == null)
continue;
if (r < midRow && c < midCol || r >= midRow && c >= midCol)
graph.findOrAddEdge(vertexB, vertexD);
else
graph.findOrAddEdge(vertexA, vertexC);
}
}
else if (diagonals == DiagonalsType.Radiating)
{
// Add diagonal edges radiating from centre
final int[][] dsteps = { { 1, 1 }, { 1,-1 }, {-1, -1}, {-1, 1} };
final int midRow = (toRow + fromRow) / 2;
final int midCol = (toCol + fromCol) / 2;
final int numSteps = Math.max((toRow - fromRow) / 2, (toCol - fromCol) / 2) + 1;
for (int n = 0; n < numSteps; n++)
{
// Add diagonals from this vertex
for (int d = 0; d < dsteps.length; d++)
{
final Vertex vertexA = graph.findVertex(midRow + n * dsteps[d][0], midCol + n * dsteps[d][1]);
final Vertex vertexB = graph.findVertex(midRow + (n + 1) * dsteps[d][0], midCol + (n + 1) * dsteps[d][1]);
if (vertexA == null || vertexB == null)
continue;
graph.findOrAddEdge(vertexA, vertexB);
}
}
}
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 8,625 | 28.744828 | 111 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/SquareShapeType.java | package game.functions.graph.generators.basis.square;
/**
* Defines known shapes for the square tiling.
*
* @author cambolbro
*/
public enum SquareShapeType
{
/** No shape; custom graph. */
NoShape,
/** Square board shape. */
Square,
/** Rectangular board shape. */
Rectangle,
/** Diamond board shape. */
Diamond,
// /** Triangular board shape. */
// Triangle,
//
// /** Hexagonal board shape. */
// Hexagon,
//
// /** Cross board shape. */
// Cross,
//
// /** Rhombus board shape. */
// Rhombus,
//
// /** Wheel board shape. */
// Wheel,
//
// /** Spiral board shape. */
// Spiral,
//
// /** Shape is derived from another graph. */
// Dual,
//
// /** Wedge shape of height N with 1 vertex at the top and 3 vertices on the bottom, for Alquerque boards. */
// Wedge,
//
// /** Multi-pointed star shape. */
// Star,
/** Alternating sides are staggered. */
Limping,
;
}
| 905 | 16.09434 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/square/package-info.java | /**
* This section contains the boards based on a square tiling.
*
*/
package game.functions.graph.generators.basis.square;
| 128 | 20.5 | 61 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/Tiling.java | package game.functions.graph.generators.basis.tiling;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.functions.graph.generators.basis.tiling.tiling31212.Tiling31212;
import game.functions.graph.generators.basis.tiling.tiling333333_33434.Tiling333333_33434;
import game.functions.graph.generators.basis.tiling.tiling33336.Tiling33336;
import game.functions.graph.generators.basis.tiling.tiling33344.CustomOn33344;
import game.functions.graph.generators.basis.tiling.tiling33344.Tiling33344;
import game.functions.graph.generators.basis.tiling.tiling33434.Tiling33434;
import game.functions.graph.generators.basis.tiling.tiling3464.CustomOn3464;
import game.functions.graph.generators.basis.tiling.tiling3464.HexagonOn3464;
import game.functions.graph.generators.basis.tiling.tiling3464.ParallelogramOn3464;
import game.functions.graph.generators.basis.tiling.tiling3636.CustomOn3636;
import game.functions.graph.generators.basis.tiling.tiling3636.Tiling3636;
import game.functions.graph.generators.basis.tiling.tiling4612.Tiling4612;
import game.functions.graph.generators.basis.tiling.tiling488.CustomOn488;
import game.functions.graph.generators.basis.tiling.tiling488.SquareOrRectangleOn488;
import game.functions.graph.operators.Keep;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board graph by a known tiling and size.
*
* @author cambolbro
*/
@SuppressWarnings("javadoc")
public class Tiling extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
@Hide
private Tiling()
{
// Make the compiler use a static construct() method.
}
//-------------------------------------------------------------------------
/**
* For defining a tiling with two dimensions.
*
* @param tiling Tiling type.
* @param dimA Number of sites along primary board dimension.
* @param dimB Number of sites along secondary board dimension [same as
* primary].
*
* @example (tiling T3636 3)
*/
public static GraphFunction construct
(
final TilingType tiling,
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
switch (tiling)
{
case T333333_33434:
return new Tiling333333_33434(dimA); // only hex shape implemented
case T3636:
return new Tiling3636(dimA, dimB);
case T33344:
return new Tiling33344(dimA, dimB);
case T488:
return new SquareOrRectangleOn488(dimA, dimB);
case T3464:
if (dimB == null)
return new HexagonOn3464(dimA);
else
return new ParallelogramOn3464(dimA, dimB);
case T4612:
return new Tiling4612(dimA); // only hex shape implemented
case T31212:
return new Tiling31212(dimA); // only hex shape implemented
case T33336:
return new Tiling33336(dimA); // only hex shape implemented
case T33434:
return new Tiling33434(dimA); // only diamond shape implemented
default:
return null;
}
}
/**
* For defining a tiling with a polygon or the number of sides.
*
* @param tiling Tiling type.
* @param poly Points defining the board shape.
* @param sides Side lengths around board in clockwise order.
*
* @example (tiling T3636 (poly { {1 2} {1 6} {3 6} } ))
* @example (tiling T3636 { 4 3 -1 2 3 })
*/
public static GraphFunction construct
(
final TilingType tiling,
@Or final Poly poly,
@Or final DimFunction[] sides
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
switch (tiling)
{
case T333333_33434:
return new Tiling333333_33434(new DimConstant(2)); // only hex shape implemented
case T3636:
return (poly != null) ? new CustomOn3636(poly.polygon()) : new CustomOn3636(sides);
case T3464:
return (poly != null) ? new CustomOn3464(poly.polygon()) : new CustomOn3464(sides);
case T33344:
return (poly != null) ? new CustomOn33344(poly.polygon()) : new CustomOn33344(sides);
case T488:
return (poly != null) ? new CustomOn488(poly.polygon()) : new CustomOn488(sides);
case T4612:
return new Tiling4612(new DimConstant(3)); // only hex shape implemented
case T31212:
return new Tiling31212(new DimConstant(3)); // only hex shape implemented
case T33336:
return new Tiling33336(new DimConstant(3)); // only hex shape implemented
case T33434:
if (poly == null)
return new Tiling33434(new DimConstant(3)); // only diamond shape implemented
else
return new Keep(new Tiling33434(new DimConstant(5)), poly); // only diamond shape implemented
default:
return null;
}
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Tiling
return null;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(final Game game)
{
return 0;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 5,619 | 30.573034 | 97 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/TilingType.java | package game.functions.graph.generators.basis.tiling;
/**
* Defines known tiling types for boards (apart from regular tilings).
*
* @author cambolbro
*/
public enum TilingType
{
// Semi-regular tilings
/** Semi-regular tiling made up of triangles and dodecagons. */
T31212,
/** Rhombitrihexahedral tiling (e.g. Kensington). */
T3464,
/** Semi-regular tiling made up of octagons with squares in the interstitial gaps. */
T488,
/** Semi-regular tiling made up of squares and pairs of triangles. */
T33434,
/** Semi-regular tiling made up of triangles around hexagons. */
T33336,
/** Semi-regular tiling made up of alternating rows of squares and triangles. */
T33344,
/** Semi-regular tiling made up of triangles and hexagons. */
T3636,
/** Semi-regular tiling made up of squares, hexagons and dodecagons. */
T4612,
// Other tilings
// /** Pentagonal tiling p4 (442). */
// TilingP4_442,
//
/** Tiling 3.3.3.3.3.3,3.3.4.3.4. */
T333333_33434,
;
}
| 992 | 20.586957 | 86 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/package-info.java | /**
* This section defines the supported geometric board tilings, apart from regular tilings.
*/
package game.functions.graph.generators.basis.tiling;
| 153 | 29.8 | 90 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling31212/Tiling31212.java | package game.functions.graph.generators.basis.tiling.tiling31212;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on the semi-regular 3.12.12 tiling.
*
* @author cambolbro
*/
@Hide
public class Tiling31212 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The x unit.
*/
public static final double ux = unit / 2;
/**
* The y unit.
*/
public static final double uy = unit * Math.sqrt(3) / 2;
/**
* The references.
*/
public static final double[][] ref = new double[12][2];
{
final double r = 1 / Math.sqrt(2 - Math.sqrt(3));
final double off = Math.PI / 12 ;
for (int s = 0; s < 12; s++)
{
final double t = s / 12.0;
final double theta = off + t * 2 * Math.PI;
ref[s][0] = r * Math.cos(theta);
ref[s][1] = r * Math.sin(theta);
//System.out.println("x=" + ref[s][0] + ", y=" + ref[s][1]);
}
}
//-------------------------------------------------------------------------
/**
* @param dim Size of board (sequencedecagons per side).
*/
public Tiling31212
(
final DimFunction dim
)
{
this.basis = BasisType.T31212;
this.shape = ShapeType.Hexagon;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0] * 2 - 1;
final int cols = dim[0] * 2 - 1;
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (Math.abs(row - col) > rows / 2)
continue;
// Determine reference octagon position
final Point2D ptRef = Tiling31212.xy(row, col);
// Add satellite points (squares and triangles)
for (int n = 0; n < Tiling31212.ref.length; n++)
{
final double x = ptRef.getX() + Tiling31212.ref[n][0];
final double y = ptRef.getY() + Tiling31212.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D.Double xy(final int row, final int col)
{
final double dx = unit * 3.7320508;
final double dy = dx * Math.sqrt(3) / 2;
return new Point2D.Double((col - 0.5 * row) * dx, row * dy);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,069 | 23.22619 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling31212/package-info.java | /**
* This section contains the boards based on the semi-regular 3.12.12 tiling.
*
*/
package game.functions.graph.generators.basis.tiling.tiling31212;
| 156 | 25.166667 | 77 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling333333_33434/Tiling333333_33434.java | package game.functions.graph.generators.basis.tiling.tiling333333_33434;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on the semi-regular 3.3.3.3.6 tiling, which is made up of
* triangles around hexagons.
*
* @author cambolbro
*/
@Hide
public class Tiling333333_33434 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The x unit.
*/
public static final double ux = unit;
/**
* The y unit.
*/
public static final double uy = unit * Math.sqrt(3) / 2;
/**
* The references.
*/
public static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * ux, 1.0 * uy },
{ 0.5 * ux, 1.0 * uy },
{ 1.0 * ux, 0.0 * uy },
{ 0.5 * ux, -1.0 * uy },
{ -0.5 * ux, -1.0 * uy },
{ -1.0 * ux, 0.0 * uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* @param dim Size of board (hexagons per side).
*
* @example (tiling333333\\_33434 3)
*/
public Tiling333333_33434
(
final DimFunction dim
)
{
this.basis = BasisType.T333333_33434;
this.shape = ShapeType.Hexagon;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0] * 2 - 1;
final int cols = dim[0] * 2 - 1;
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (Math.abs(row - col) > rows / 2)
continue;
// Determine reference octagon position
final Point2D ptRef = Tiling333333_33434.xy(row, col);
// Add satellite points (squares and triangles)
for (int n = 0; n < Tiling333333_33434.ref.length; n++)
{
final double x = ptRef.getX() + Tiling333333_33434.ref[n][0];
final double y = ptRef.getY() + Tiling333333_33434.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D.Double xy(final int row, final int col)
{
final double hx = unit * (1.5 + Math.sqrt(3));
final double hy = unit * (2 + Math.sqrt(3));
return new Point2D.Double(hx * (col - row), hy * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,525 | 24.144444 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling33336/Tiling33336.java | package game.functions.graph.generators.basis.tiling.tiling33336;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on the semi-regular 3.3.3.3.6 tiling, which is made up of
* triangles around hexagons.
*
* @author cambolbro
*/
@Hide
public class Tiling33336 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The x unit.
*/
public static final double ux = unit / 2;
/**
* The y unit.
*/
public static final double uy = unit * Math.sqrt(3) / 2;
/**
* The references.
*/
public static final double[][] ref =
{
// Central hexagon
{ -1 * ux, 1 * uy },
{ 1 * ux, 1 * uy },
{ 2 * ux, 0 * uy },
{ 1 * ux, -1 * uy },
{ -1 * ux, -1 * uy },
{ -2 * ux, 0 * uy },
// Surrounding triangles
{ -2 * ux, 2 * uy },
{ 0 * ux, 2 * uy },
{ 2 * ux, 2 * uy },
{ 3 * ux, 1 * uy },
{ 4 * ux, 0 * uy },
{ 3 * ux, -1 * uy },
{ 2 * ux, -2 * uy },
{ 0 * ux, -2 * uy },
{ -2 * ux, -2 * uy },
{ -3 * ux, -1 * uy },
{ -4 * ux, 0 * uy },
{ -3 * ux, 1 * uy },
};
//-------------------------------------------------------------------------
/**
* @param dim Size of board (hexagons per side).
*
* @example (tiling33336 3)
*/
public Tiling33336
(
final DimFunction dim
)
{
this.basis = BasisType.T33336;
this.shape = ShapeType.Hexagon;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0] * 2 - 1;
final int cols = dim[0] * 2 - 1;
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (Math.abs(row - col) > rows / 2)
continue;
// Determine reference octagon position
final Point2D ptRef = Tiling33336.xy(row, col);
// Add satellite points (squares and triangles)
for (int n = 0; n < Tiling33336.ref.length; n++)
{
final double x = ptRef.getX() + Tiling33336.ref[n][0];
final double y = ptRef.getY() + Tiling33336.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D.Double xy(final int row, final int col)
{
return new Point2D.Double(col * 5 * ux - row * 4 * ux, row * 2 * uy + col * uy);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,218 | 22.971591 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling33344/CustomOn33344.java | package game.functions.graph.generators.basis.tiling.tiling33344;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a custom board shape on the semi-regular 3.3.3.4.4 tiling.
*
* @author cambolbro
*
* The semi-regular 3.3.3.4.4 tiling is composed of alternating rows of squares and triangles.
*/
@Hide
public class CustomOn33344 extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hexagonal.
*
* @param polygon The polygon.
*/
public CustomOn33344
(
final Polygon polygon
)
{
this.basis = BasisType.T33344;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The index of the sides.
*/
public CustomOn33344
(
final DimFunction[] sides
)
{
this.basis = BasisType.T33344;
this.shape = (sides.length == 2 && sides[0].eval() == sides[1].eval() - 1)
? ShapeType.Limping
: ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (polygon.isEmpty() && !sides.isEmpty())
polygonFromSides();
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
final int fromCol = (int)bounds.getMinX() - 2;
final int fromRow = (int)bounds.getMinY() - 2;
final int toCol = (int)bounds.getMaxX() + 2;
final int toRow = (int)bounds.getMaxY() + 2;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
final Point2D ptRef = Tiling33344.xy(r, c);
if (!polygon.contains(ptRef))
continue;
for (int n = 0; n < Tiling33344.ref.length; n++)
{
final double x = ptRef.getX() + Tiling33344.ref[n][1];
final double y = ptRef.getY() + Tiling33344.ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* Generate polygon from the description of sides.
*
* Can't really distinguish Cell from Vertex versions here (-ve turns make
* ambiguous cases) so treat both the same.
*/
void polygonFromSides()
{
final int[][] steps = { {1, 0}, {1, 1}, {0, 1}, {-1, 0}, {-1, -1}, {0, -1} };
int step = 1;
int row = 0;
int col = 0;
polygon.clear();
polygon.add(Tiling33344.xy(row, col));
for (int n = 0; n < Math.max(5, sides.size()); n++)
{
int nextStep = sides.get(n % sides.size());
// Always reduce by 1
if (nextStep < 0)
nextStep += 1;
else
nextStep -= 1;
if (nextStep < 0)
step -= 1;
else
step += 1;
step = (step + 6) % 6; // keep in range
if (nextStep > 0)
{
row += nextStep * steps[step][0];
col += nextStep * steps[step][1];
polygon.add(Tiling33344.xy(row, col));
}
}
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,916 | 22.985366 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling33344/Tiling33344.java | package game.functions.graph.generators.basis.tiling.tiling33344;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on a semi-regular 3.3.3.4.4 tiling.
*
* @author cambolbro
*
* Tiling 3.3.3.4.4 is composed of rows of triangles and squares.
*/
@Hide
public class Tiling33344 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The references.
*/
public static final double[][] ref =
{
{ 0, 0 },
{ 0, unit },
{ unit, unit },
{ unit, 0 },
};
//-------------------------------------------------------------------------
/**
* @param dimA Number of rows (in squares).
* @param dimB Number of columns (in squares).
*
* @example (tiling33344 3 4)
*/
public Tiling33344
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
this.basis = BasisType.T33344;
this.shape = ShapeType.Rhombus;
this.dim = new int[] { dimA.eval(), (dimB == null ? dimA.eval() : dimB.eval()) };
}
/**
* @param poly Points defining the board shape.
* @param sides Side lengths around board in clockwise order.
*
* @example (tiling33344 (poly { {1 2} {1 6} {3 6} } ))
* @example (tiling33344 { 4 3 -1 2 3 })
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Or final Poly poly,
@Or final DimFunction[] sides
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
if (poly != null)
return new CustomOn33344(poly.polygon());
else
return new CustomOn33344(sides);
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[1];
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
final Point2D ptRef = Tiling33344.xy(row, col);
for (int n = 0; n < Tiling33344.ref.length; n++)
{
final double x = ptRef.getX() + Tiling33344.ref[n][1];
final double y = ptRef.getY() + Tiling33344.ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D xy(final int row, final int col)
{
final double dx = unit;
final double dy = unit * (1 + Math.sqrt(3) / 2);
return new Point2D.Double((col + 0.5 * row) * dx, row *dy);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,509 | 23.247312 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling33434/Tiling33434.java | package game.functions.graph.generators.basis.tiling.tiling33434;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on the 3.3.4.3.4 tiling, which is made up of squares and
* pairs of triangles.
*
* @author cambolbro
*
* @remarks This semi-regular tiling is the dual of the Cairo tiling.
*/
@Hide
public class Tiling33434 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private static final double u2 = unit / 2;
private static final double u3 = unit * Math.sqrt(3) / 2;
/**
* The references.
*/
public static final double[][] ref =
{
// Store sub-tile point positions
{ -1 * u2 + 0 * u3, -1 * u2 - 1 * u3 },
{ 1 * u2 + 0 * u3, -1 * u2 - 1 * u3 },
{ -1 * u2 - 1 * u3, 0 * u2 - 1 * u3 },
{ 1 * u2 + 1 * u3, 0 * u2 - 1 * u3 },
{ 0 * u2 + 0 * u3, -1 * u2 + 0 * u3 },
{ -2 * u2 - 1 * u3, 0 * u2 + 0 * u3 },
{ 0 * u2 - 1 * u3, 0 * u2 + 0 * u3 },
{ 0 * u2 + 1 * u3, 0 * u2 + 0 * u3 },
{ 2 * u2 + 1 * u3, 0 * u2 + 0 * u3 },
{ 0 * u2 + 0 * u3, 1 * u2 + 0 * u3 },
{ -1 * u2 - 1 * u3, 0 * u2 + 1 * u3 },
{ 1 * u2 + 1 * u3, 0 * u2 + 1 * u3 },
{ -1 * u2 + 0 * u3, 1 * u2 + 1 * u3 },
{ 1 * u2 + 0 * u3, 1 * u2 + 1 * u3 },
};
//-------------------------------------------------------------------------
/**
* @param dim Size of board.
*
* @example (tiling33434 4)
*/
public Tiling33434
(
final DimFunction dim
)
{
this.basis = BasisType.T33434;
this.shape = ShapeType.Diamond;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[0];
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
// Determine reference octagon position
final Point2D ptRef = Tiling33434.xy(r, c);
// Add satellite points (squares and triangles)
for (int n = 0; n < Tiling33434.ref.length; n++)
{
final double x = ptRef.getX() + Tiling33434.ref[n][0];
final double y = ptRef.getY() + Tiling33434.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D.Double xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3)) / 2;
final double hy = hx;
return new Point2D.Double(hx * (col - row), hy * (row + col));
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,334 | 25.272727 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/CustomOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a custom board for the 3.4.6.4 tiling.
*
* @author cambolbro
*
*/
@Hide
public class CustomOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tiling3464.
*
* @param polygon The polygon.
*/
public CustomOn3464(final Polygon polygon)
{
this.basis = BasisType.T3464;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The indices of the sides.
*/
public CustomOn3464(final DimFunction[] sides)
{
this.basis = BasisType.T3464;
this.shape = (sides.length == 2 && sides[0].eval() == sides[1].eval() - 1)
? ShapeType.Limping
: ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (polygon.isEmpty() && !sides.isEmpty())
//polygon.fromSides(sides, Tiling3464.steps);
polygonFromSides();
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
final int fromCol = (int)bounds.getMinX() - 2;
final int fromRow = (int)bounds.getMinY() - 2;
final int toCol = (int)bounds.getMaxX() + 2;
final int toRow = (int)bounds.getMaxY() + 2;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
final Point2D ptRef = xy(r, c);
if (!polygon.contains(ptRef))
continue;
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][1];
final double y = ptRef.getY() + ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph result = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
result.reorder();
return result;
}
//-------------------------------------------------------------------------
/**
* Generate polygon from the description of sides.
*
* Can't really distinguish Cell from Vertex versions here (-ve turns make
* ambiguous cases) so treat both the same.
*/
void polygonFromSides()
{
final int[][] steps = { {1, 0}, {1, 1}, {0, 1}, {-1, 0}, {-1, -1}, {0, -1} };
int dirn = 1;
int row = 0;
int col = 0;
polygon.clear();
polygon.add(Tiling3464.xy(row, col));
for (int n = 0; n < Math.max(5, sides.size()); n++)
{
int nextStep = sides.get(n % sides.size());
// Always reduce by 1
if (nextStep < 0)
nextStep += 1;
else
nextStep -= 1;
if (nextStep < 0)
dirn -= 1;
else
dirn += 1;
dirn = (dirn + 6) % 6; // keep in range
if (nextStep > 0)
{
row += nextStep * steps[dirn][0];
col += nextStep * steps[dirn][1];
polygon.add(xy(row, col));
}
}
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,910 | 24.153191 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/DiamondOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a diamond (i.e. rhombus) shaped hex board on a 3.4.6.4 tiling.
*
* @author cambolbro
*
* @remarks A diamond on a hexagonal grid is a rhombus, as used in the game Hex.
*/
@Hide
public class DiamondOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private static final double ux = unit;
private static final double uy = unit * Math.sqrt(3) / 2.0;
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * ux, 1.0 * uy },
{ 0.5 * ux, 1.0 * uy },
{ 1.0 * ux, 0.0 * uy },
{ 0.5 * ux, -1.0 * uy },
{ -0.5 * ux, -1.0 * uy },
{ -1.0 * ux, 0.0 * uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public DiamondOn3464
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
this.basis = BasisType.T3464;
this.shape = (dimB == null) ? ShapeType.Diamond : ShapeType.Prism;
this.dim = (dimB == null)
? new int[]{ dimA.eval() }
: new int[]{ dimA.eval(), dimB.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final boolean isPrism = (shape == ShapeType.Prism);
final int rows = dim[0];
final int cols = (isPrism ? dim[1] : dim[0]);
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
if (isPrism)
{
for (int r = 0; r < rows + cols - 1; r++)
for (int c = 0; c < cols + rows - 1; c++)
{
if (Math.abs(r - c) >= rows)
continue;
addVertex(r, c, vertexList);
}
}
else
{
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
addVertex(r, c, vertexList);
}
final Graph result = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
result.reorder();
return result;
}
//-------------------------------------------------------------------------
static void addVertex(final int row, final int col, final List<double[]> vertexList)
{
final Point2D ptRef = xy(row, col);
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][0];
final double y = ptRef.getY() + ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hy * (col - row), hx * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
if (shape.equals(ShapeType.Diamond))
concepts.set(Concept.DiamondShape.id(), true);
else
concepts.set(Concept.PrismShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,857 | 24.568421 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/HexagonOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a hexagonal rhombitrihexahedral (semi-regular tiling 3.4.6.4) board.
*
* @author cambolbro
*/
@Hide
public class HexagonOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tiling3464.
*
* @param dim The dimension.
*/
public HexagonOn3464
(
final DimFunction dim
)
{
this.basis = BasisType.T3464;
this.shape = ShapeType.Hexagon;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = 2 * dim[0] - 1;
final int cols = 2 * dim[0] - 1;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (c > cols / 2 + r || r - c > cols / 2)
continue;
// Determine reference hexagon position
final Point2D ptRef = xy(r, c);
// Add satellite points (hexagon and extended square points) relative to reference hexagons
for (int n = 0; n < Tiling3464.ref.length; n++)
{
final double x = ptRef.getX() + ref[n][0];
final double y = ptRef.getY() + ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph result = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
result.reorder();
return result;
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hy * (col - row), hx * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.HexShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,279 | 25.419753 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/ParallelogramOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a diamond (i.e. rhombus) shaped hex board on a 3.4.6.4 tiling.
*
* @author cambolbro
*
* @remarks A diamond on a hexagonal grid is a rhombus, as used in the game Hex.
*/
@Hide
public class ParallelogramOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private static final double ux = unit;
private static final double uy = unit * Math.sqrt(3) / 2.0;
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * ux, 1.0 * uy },
{ 0.5 * ux, 1.0 * uy },
{ 1.0 * ux, 0.0 * uy },
{ 0.5 * ux, -1.0 * uy },
{ -0.5 * ux, -1.0 * uy },
{ -1.0 * ux, 0.0 * uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public ParallelogramOn3464
(
final DimFunction dimA,
final DimFunction dimB
)
{
this.basis = BasisType.T3464;
this.shape = ShapeType.Quadrilateral;
this.dim = new int[]{ dimA.eval(), dimB.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[1];
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
addVertex(row, col, vertexList);
final Graph result = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
result.reorder();
return result;
}
//-------------------------------------------------------------------------
static void addVertex(final int row, final int col, final List<double[]> vertexList)
{
final Point2D ptRef = xy(row, col);
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][0];
final double y = ptRef.getY() + ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hy * (col - row), hx * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.ParallelogramShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,361 | 24.810651 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/RectangleOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangle shaped board with a 3.4.6.4 tiling.
*
* @author cambolbro
*/
@Hide
public class RectangleOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private static final double ux = unit;
private static final double uy = unit * Math.sqrt(3) / 2.0;
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * ux, 1.0 * uy },
{ 0.5 * ux, 1.0 * uy },
{ 1.0 * ux, 0.0 * uy },
{ 0.5 * ux, -1.0 * uy },
{ -0.5 * ux, -1.0 * uy },
{ -1.0 * ux, 0.0 * uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tiling3464.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public RectangleOn3464
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
final int rows = dimA.eval();
final int cols = (dimB != null) ? dimB.eval() : rows;
this.basis = BasisType.T3464;
this.shape = (rows == cols) ? ShapeType.Square : ShapeType.Rectangle;
this.dim = new int[]{ rows, cols };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[1];
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols + rows; c++)
{
if (c < (r + 1) / 2 || c >= cols + r / 2)
continue;
final Point2D ptRef = xy(r, c);
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][1];
final double y = ptRef.getY() + ref[n][0];
// Check if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph result = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
result.reorder();
return result;
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
if (shape.equals(ShapeType.Square))
concepts.set(Concept.SquareShape.id(), true);
else
concepts.set(Concept.RectangleShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,391 | 24.684211 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/StarOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a six-pointed star board on a hexagonal grid.
*
* @author cambolbro
*/
@Hide
public class StarOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = BaseGraphFunction.unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tiling3464.
*
* @param dim The dimension.
*/
public StarOn3464
(
final DimFunction dim
)
{
this.basis = BasisType.T3464;
this.shape = ShapeType.Star;
this.dim = new int[]{ dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int d = dim[0];
final int rows = 4 * dim[0] + 1;
final int cols = 4 * dim[0] + 1;
//final Graph graph = new Graph();
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r < d && (c < d || c - r > d))
{
continue;
}
else if (r <= 2 * d)
{
if (r - c > d || c >= cols - d)
continue;
}
else if (r <= 3 * d)
{
if (c < d || c - r > d)
continue;
}
else if (c > 3 * d || r - c > d)
{
continue;
}
final Point2D ptRef = xy(r, c);
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][1];
final double y = ptRef.getY() + ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
//graph.addVertex(x, y);
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, BaseGraphFunction.unit, basis,
shape);
//graph.createUnitEdges(Tiling3464.u);
//graph.createFaces();
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.StarShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,526 | 23.737705 | 108 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/Tiling3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.dim.math.Add;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.util.graph.Poly;
import other.concept.Concept;
//-----------------------------------------------------------------------------
/**
* Defines a board on a rhombitrihexahedral tiling (semi-regular tiling 3.4.6.4),
* such as the Kensington board.
*
* @author cambolbro
*/
@Hide
public class Tiling3464 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The x unit.
*/
public static final double ux = unit;
/**
* The y unit.
*/
public static final double uy = unit * Math.sqrt(3) / 2;
/**
* The references.
*/
public static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * ux, 1.0 * uy },
{ 0.5 * ux, 1.0 * uy },
{ 1.0 * ux, 0.0 * uy },
{ 0.5 * ux, -1.0 * uy },
{ -0.5 * ux, -1.0 * uy },
{ -1.0 * ux, 0.0 * uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* @param shape Board shape [Hexagon].
* @param dimA Board dimension; major hex cells per side.
* @param dimB Board dimension; major hex cells per side.
*
* @example (tiling3464 2)
* @example (tiling3464 Limping 3)
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Opt final Tiling3464ShapeType shape,
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
final Tiling3464ShapeType st = (shape == null) ? Tiling3464ShapeType.Hexagon : shape;
switch (st)
{
case Hexagon:
return new HexagonOn3464(dimA);
case Triangle:
return new TriangleOn3464(dimA);
case Diamond:
return new DiamondOn3464(dimA, null);
case Prism:
return new DiamondOn3464(dimA, (dimB != null ? dimB : dimA));
case Star:
return new StarOn3464(dimA);
case Limping:
final DimFunction dimAplus1 = new Add(dimA, new DimConstant(1));
return new CustomOn3464(new DimFunction[] { dimA, dimAplus1 } );
case Square:
return new RectangleOn3464(dimA, dimA);
case Rectangle:
return new RectangleOn3464(dimA, (dimB != null ? dimB : dimA));
default:
throw new IllegalArgumentException("Shape " + st + " not supported for tiling3464.");
}
}
/**
* @param poly Points defining the board shape.
* @param sides Side lengths around board in clockwise order.
*
* @example (tiling3464 (poly { {1 2} {1 6} {3 6} {3 4} } ))
* @example (tiling3464 { 4 3 -1 2 3 })
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Or final Poly poly,
@Or final DimFunction[] sides
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
if (poly != null)
return new CustomOn3464(poly.polygon());
else
return new CustomOn3464(sides);
}
//-------------------------------------------------------------------------
private Tiling3464()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hx * (col - row), hy * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,915 | 24.604167 | 89 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/Tiling3464ShapeType.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.util.BitSet;
import game.Game;
import metadata.graphics.GraphicsItem;
/**
* Defines known shapes for the rhombitrihexahedral (semi-regular 3.4.6.4) tiling.
*
* @author cambolbro
*/
public enum Tiling3464ShapeType implements GraphicsItem
{
// /** No defined shape. */
// NoShape,
/** Custom board shape. */
Custom,
/** Square board shape. */
Square,
/** Rectangular board shape. */
Rectangle,
/** Diamond board shape. */
Diamond,
/** Diamond board shape extended vertically. */
Prism,
/** Triangular board shape. */
Triangle,
/** Hexagonal board shape. */
Hexagon,
// /** Cross board shape. */
// Cross,
//
// /** Rhombus board shape. */
// Rhombus,
//
// /** Wheel board shape. */
// Wheel,
//
// /** Spiral board shape. */
// Spiral,
//
// /** Shape is derived from another graph. */
// Dual,
//
// /** Wedge shape of height N with 1 vertex at the top and 3 vertices on the bottom, for Alquerque boards. */
// Wedge,
/** Multi-pointed star shape. */
Star,
/** Alternating sides are staggered. */
Limping,
;
//-------------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
return concepts;
}
@Override
public long gameFlags(final Game game)
{
final long gameFlags = 0l;
return gameFlags;
}
@Override
public boolean needRedraw()
{
return false;
}
}
| 1,519 | 16.674419 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/TriangleOn3464.java | package game.functions.graph.generators.basis.tiling.tiling3464;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangle shaped board with a 3.4.6.4 tiling.
*
* @author cambolbro
*/
@Hide
public class TriangleOn3464 extends Basis
{
private static final long serialVersionUID = 1L;
private static final double[][] ref =
{
// Store major hexagon point position
{ -0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, 1.0 * Tiling3464.uy },
{ 1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -0.5 * Tiling3464.ux, -1.0 * Tiling3464.uy },
{ -1.0 * Tiling3464.ux, 0.0 * Tiling3464.uy },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
};
{
// Calculate outer square point positions
final double a = BaseGraphFunction.unit + Math.sqrt(3) / 2.0;
final double h = a / Math.cos(Math.toRadians(15));
for (int n = 0; n < 12; n++)
{
final double theta = Math.toRadians(15 + n * 30);
ref[6 + n][0] = h * Math.cos(theta);
ref[6 + n][1] = h * Math.sin(theta);
}
}
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hex.
*
* @param dim The dimension.
*/
public TriangleOn3464
(
final DimFunction dim
)
{
this.basis = BasisType.Hexagonal;
this.shape = ShapeType.Triangle;
this.dim = new int[]{ dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = dim[0];
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r > c)
continue;
final Point2D ptRef = xy(r, c);
for (int n = 0; n < ref.length; n++)
{
final double x = ptRef.getX() + ref[n][1];
final double y = ptRef.getY() + ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph result = BaseGraphFunction.createGraphFromVertexList(vertexList, BaseGraphFunction.unit, basis,
shape);
result.reorder();
return result;
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit * (1 + Math.sqrt(3));
final double hy = unit * (3 + Math.sqrt(3)) / 2;
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.TriangleShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,092 | 24.58125 | 109 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3464/package-info.java | /**
* This section contains the boards based on a rhombitrihexahedral tiling (semi-regular tiling 3.4.6.4),
* such as the tiling used for the Kensington board.
*/
package game.functions.graph.generators.basis.tiling.tiling3464;
| 232 | 37.833333 | 105 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3636/CustomOn3636.java | package game.functions.graph.generators.basis.tiling.tiling3636;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a custom board shape on the hexagonal tiling.
*
* @author cambolbro
*
*/
@Hide
public class CustomOn3636 extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Hexagonal.
*
* @param polygon The polygon.
*/
public CustomOn3636
(
final Polygon polygon
)
{
this.basis = BasisType.Hexagonal;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The indices of the sides.
*/
public CustomOn3636
(
final DimFunction[] sides
)
{
this.basis = BasisType.Hexagonal;
this.shape = (sides.length == 2 && sides[0].eval() == sides[1].eval() - 1)
? ShapeType.Limping
: ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (polygon.isEmpty() && !sides.isEmpty())
polygonFromSides();
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
final int fromCol = (int)bounds.getMinX() - 2;
final int fromRow = (int)bounds.getMinY() - 2;
final int toCol = (int)bounds.getMaxX() + 2;
final int toRow = (int)bounds.getMaxY() + 2;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
final Point2D ptRef = Tiling3636.xy(r, c);
if (!polygon.contains(ptRef))
continue;
for (int n = 0; n < Tiling3636.ref.length; n++)
{
final double x = ptRef.getX() + Tiling3636.ref[n][1];
final double y = ptRef.getY() + Tiling3636.ref[n][0];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* Generate polygon from the description of sides.
*
* Can't really distinguish Cell from Vertex versions here (-ve turns make
* ambiguous cases) so treat both the same.
*/
void polygonFromSides()
{
final int[][] steps = { {1, 0}, {1, 1}, {0, 1}, {-1, 0}, {-1, -1}, {0, -1} };
int step = 1;
int row = 0;
int col = 0;
polygon.clear();
polygon.add(Tiling3636.xy(row, col));
for (int n = 0; n < Math.max(5, sides.size()); n++)
{
int nextStep = sides.get(n % sides.size());
// Always reduce by 1
if (nextStep < 0)
nextStep += 1;
else
nextStep -= 1;
if (nextStep < 0)
step -= 1;
else
step += 1;
step = (step + 6) % 6; // keep in range
if (nextStep > 0)
{
row += nextStep * steps[step][0];
col += nextStep * steps[step][1];
polygon.add(Tiling3636.xy(row, col));
}
}
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,807 | 22.568627 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling3636/Tiling3636.java | package game.functions.graph.generators.basis.tiling.tiling3636;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on a semi-regular 3.6.3.6 tiling.
*
* @author cambolbro
*
* Tiling 3.6.3.6 is composed of triangles and hexagons.
*/
@Hide
public class Tiling3636 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The x unit.
*/
public static final double ux = unit * Math.sqrt(3) / 2;
/**
* The y unit.
*/
public static final double uy = unit;
/**
* The references.
*/
public static final double[][] ref =
{
{ 0.0 * ux, 1.0 * uy },
{ 1.0 * ux, 0.5 * uy },
{ 1.0 * ux, -0.5 * uy },
{ 0.0 * ux, -1.0 * uy },
{ -1.0 * ux, -0.5 * uy },
{ -1.0 * ux, 0.5 * uy },
};
//-------------------------------------------------------------------------
/**
* @param dimA Primary board dimension; cells or vertices per side.
* @param dimB Secondary Board dimension; cells or vertices per side.
*/
public Tiling3636
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
this.basis = BasisType.T3636;
if (dimB == null)
{
this.shape = ShapeType.Hexagon;
this.dim = new int[]{ dimA.eval() };
}
else
{
this.shape = ShapeType.Rhombus;
this.dim = new int[]{ dimA.eval(), dimB.eval() };
}
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = 2 * dim[0] - 1;
final int cols = 2 * (dim.length < 2 ? dim[0] : dim[1]) - 1;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (shape == ShapeType.Hexagon && (col > cols / 2 + row || row - col > cols / 2))
continue;
if (shape == ShapeType.Triangle && row > col)
continue;
final Point2D ptRef = Tiling3636.xy(row, col);
for (int n = 0; n < Tiling3636.ref.length; n++)
{
final double x = ptRef.getX() + Tiling3636.ref[n][1];
final double y = ptRef.getY() + Tiling3636.ref[n][0];
// See if vertex is already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D xy(final int row, final int col)
{
final double hx = 2;
final double hy = Math.sqrt(3);
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,262 | 23.084746 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling4612/Tiling4612.java | package game.functions.graph.generators.basis.tiling.tiling4612;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on the semi-regular 4.6.12 tiling.
*
* @author cambolbro
*/
@Hide
public class Tiling4612 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* The x unit.
*/
public static final double ux = unit / 2;
/**
* The y unit.
*/
public static final double uy = unit * Math.sqrt(3) / 2;
/**
* The references.
*/
public static final double[][] ref = new double[12][2];
{
final double r = 1 / Math.sqrt(2 - Math.sqrt(3));
final double off = Math.PI / 12 ;
for (int s = 0; s < 12; s++)
{
final double t = s / 12.0;
final double theta = off + t * 2 * Math.PI;
ref[s][0] = r * Math.cos(theta);
ref[s][1] = r * Math.sin(theta);
//System.out.println("x=" + ref[s][0] + ", y=" + ref[s][1]);
}
}
//-------------------------------------------------------------------------
/**
* @param dim Size of board (sequencedecagons per side).
*
* @example (tiling4612 2)
*/
public Tiling4612
(
final DimFunction dim
)
{
this.basis = BasisType.T4612;
this.shape = ShapeType.Hexagon;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0] * 2 - 1;
final int cols = dim[0] * 2 - 1;
final List<double[]> vertexList = new ArrayList<double[]>();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (Math.abs(row - col) > rows / 2)
continue;
// Determine reference octagon position
final Point2D ptRef = Tiling4612.xy(row, col);
// Add satellite points (squares and triangles)
for (int n = 0; n < Tiling4612.ref.length; n++)
{
final double x = ptRef.getX() + Tiling4612.ref[n][0];
final double y = ptRef.getY() + Tiling4612.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D.Double xy(final int row, final int col)
{
final double dx = unit * 4.7320508;
final double dy = dx * Math.sqrt(3) / 2;
return new Point2D.Double((col - 0.5 * row) * dx, row * dy);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,092 | 23.076471 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling488/CustomOn488.java | package game.functions.graph.generators.basis.tiling.tiling488;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.MathRoutines;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a custom board on the 4.8.8 tiling.
*
* @author cambolbro
*
*/
@Hide
public class CustomOn488 extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Square.
*
* @param polygon The polygon.
*/
public CustomOn488(final Polygon polygon)
{
this.basis = BasisType.T488;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The indices of the sides.
*/
public CustomOn488
(
final DimFunction[] sides
)
{
this.basis = BasisType.T488;
this.shape = ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int[][] steps = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
if (polygon.isEmpty() && !sides.isEmpty())
polygon.fromSides(sides, steps);
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
final int fromCol = (int)bounds.getMinX() - 2;
final int fromRow = (int)bounds.getMinY() - 2;
final int toCol = (int)bounds.getMaxX() + 2;
final int toRow = (int)bounds.getMaxY() + 2;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
// Determine reference octagon position
final Point2D.Double ptRef = Tiling488.xy(r, c);
if (polygon.contains(ptRef))
{
// Add satellite points (octagon vertices)
for (int n = 0; n < Tiling488.ref.length; n++)
{
final double x = ptRef.getX() + Tiling488.ref[n][0];
final double y = ptRef.getY() + Tiling488.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[]{ x, y });
}
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, BaseGraphFunction.unit, basis,
shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// ...
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,910 | 23.910828 | 108 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling488/SquareOrRectangleOn488.java | package game.functions.graph.generators.basis.tiling.tiling488;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a square or rectangular board on the 4.8.8 tiling.
*
* @author cambolbro
*
*/
@Hide
public class SquareOrRectangleOn488 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Square.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public SquareOrRectangleOn488
(
final DimFunction dimA,
final DimFunction dimB
)
{
this.basis = BasisType.T488;
this.shape = (dimB == null || dimA == dimB) ? ShapeType.Square : ShapeType.Rectangle;
if (dimB == null || dimA == dimB)
this.dim = new int[] { dimA.eval() };
else
this.dim = new int[] { dimA.eval(), dimB.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int cols = (dim.length > 1) ? dim[1] : dim[0];
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
// Determine reference octagon position
final Point2D ptRef = Tiling488.xy(r, c);
// Add satellite points (vertices of octagon)
for (int n = 0; n < Tiling488.ref.length; n++)
{
final double x = ptRef.getX() + Tiling488.ref[n][0];
final double y = ptRef.getY() + Tiling488.ref[n][1];
// See if vertex already created
int vid;
for (vid = 0; vid < vertexList.size(); vid++)
{
final double[] ptV = vertexList.get(vid);
final double dist = MathRoutines.distance(ptV[0], ptV[1], x, y);
if (dist < 0.1)
break;
}
if (vid >= vertexList.size())
vertexList.add(new double[] { x, y });
}
}
return BaseGraphFunction.createGraphFromVertexList(vertexList, 1, basis, shape);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
if (shape.equals(ShapeType.Square))
concepts.set(Concept.SquareShape.id(), true);
else
concepts.set(Concept.RectangleShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,350 | 25.179688 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tiling/tiling488/Tiling488.java | package game.functions.graph.generators.basis.tiling.tiling488;
import java.awt.geom.Point2D;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.graph.generators.basis.Basis;
import other.concept.Concept;
//-----------------------------------------------------------------------------
/**
* Defines a board on the 4.8.8 tiling, which is made up of octagons with
* squares in the interstitial gaps.
*
* @author cambolbro
*
* @remarks Rotating this semi-regular tiling 45 degrees leave the octagons
* in the same relative relation, but the square angled.
*/
@Hide
public class Tiling488 extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private static final double u = unit;
private static final double v = unit * (1 + 2 / Math.sqrt(2));
/**
* The references.
*/
public static final double[][] ref =
{
// Store major octagon point positions
{ u / 2, v / 2 },
{ v / 2, u / 2 },
{ v / 2, -u / 2 },
{ u / 2, -v / 2 },
{ -u / 2, -v / 2 },
{ -v / 2, -u / 2 },
{ -v / 2, u / 2 },
{ -u / 2, v / 2 },
};
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D.Double xy(final int row, final int col)
{
return new Point2D.Double(col * v, row * v);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SemiRegularTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,032 | 22.367816 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/CustomOnTri.java | package game.functions.graph.generators.basis.tri;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import gnu.trove.list.array.TIntArrayList;
import main.math.Polygon;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a rectangular board.
*
* @author cambolbro
*
*/
@Hide
public class CustomOnTri extends Basis
{
private static final long serialVersionUID = 1L;
private final Polygon polygon = new Polygon();
private final TIntArrayList sides = new TIntArrayList();
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Triangular.
*
* @param polygon The polygon.
*/
public CustomOnTri
(
final Polygon polygon
)
{
this.basis = BasisType.Triangular;
this.shape = ShapeType.Custom;
this.polygon.setFrom(polygon);
}
/**
* Hidden constructor, is a helper for Square.
*
* @param sides The indices of the sides.
*/
public CustomOnTri
(
final DimFunction[] sides
)
{
this.basis = BasisType.Triangular;
this.shape = (sides.length == 2 && sides[0].eval() == sides[1].eval() - 1)
? ShapeType.Limping
: ShapeType.Custom;
for (int n = 0; n < sides.length; n++)
this.sides.add(sides[n].eval());
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (polygon.isEmpty() && !sides.isEmpty())
polygonFromSides(siteType);
polygon.inflate(0.1);
final Rectangle2D bounds = polygon.bounds();
// If limping boards (or any other shapes) have missing cells,
// then increase the following margins.
final int margin = (shape == ShapeType.Limping && sides != null) ? sides.get(0) : 2;
final int fromCol = (int)bounds.getMinX() - margin;
final int fromRow = (int)bounds.getMinY() - margin;
final int toCol = (int)bounds.getMaxX() + margin;
final int toRow = (int)bounds.getMaxY() + margin;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = fromRow; r <= toRow; r++)
for (int c = fromCol; c <= toCol; c++)
{
final Point2D pt = Tri.xy(r, c);
if (!polygon.contains(pt))
continue;
vertexList.add(new double[]{ pt.getX(), pt.getY() });
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
/**
* Generate polygon from the description of sides.
*
* Can't really distinguish Cell from Vertex versions here (-ve turns make
* ambiguous cases) so treat both the same.
*/
void polygonFromSides(final SiteType siteType)
{
final int[][] steps = { {1, 0}, {1, 1}, {0, 1}, {-1, 0}, {-1, -1}, {0, -1} };
int dirn = 1;
int row = 0;
int col = 0;
polygon.clear();
polygon.add(Tri.xy(row, col));
for (int n = 0; n < Math.max(5, sides.size()); n++)
{
int nextStep = sides.get(n % sides.size());
// Always reduce by 1
//if (siteType != SiteType.Cell)
{
if (nextStep < 0)
nextStep += 1;
else
nextStep -= 1;
}
if (nextStep < 0)
dirn -= 1;
else
dirn += 1;
dirn = (dirn + 6) % 6; // keep in range
if (nextStep > 0)
{
row += nextStep * steps[dirn][0];
col += nextStep * steps[dirn][1];
polygon.add(Tri.xy(row, col));
}
}
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.TriangleTiling.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 4,514 | 22.515625 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/DiamondOnTri.java | package game.functions.graph.generators.basis.tri;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a diamond (i.e. rhombus) shaped hex board on a triangular tiling.
*
* @author cambolbro
*
* @remarks A diamond on a triangular grid is a rhombus, as used in the game Hex.
*/
@Hide
public class DiamondOnTri extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tri.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public DiamondOnTri
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
this.basis = BasisType.Triangular;
this.shape = (dimB == null) ? ShapeType.Diamond : ShapeType.Prism;
this.dim = (dimB == null)
? new int[]{ dimA.eval() }
: new int[]{ dimA.eval(), dimB.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final boolean isPrism = (shape == ShapeType.Prism);
final int rows = dim[0] + (siteType == SiteType.Cell ? 1 : 0);
final int cols = (isPrism ? dim[1] : dim[0]) + (siteType == SiteType.Cell ? 1 : 0);
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
if (isPrism)
{
for (int r = 0; r < rows + cols - 1; r++)
for (int c = 0; c < cols + rows - 1; c++)
{
if (Math.abs(r - c) >= rows)
continue;
final Point2D pt = xy(r, c);
vertexList.add(new double[] { pt.getX(), pt.getY() });
}
}
else
{
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
final Point2D pt = xy(r, c);
vertexList.add(new double[] { pt.getX(), pt.getY() });
}
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
static Point2D xy(final int row, final int col)
{
final double hx = unit;
final double hy = Math.sqrt(3) / 2.0;
return new Point2D.Double(hy * (col - row), hx * (row + col) * 0.5);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.TriangleTiling.id(), true);
if (shape.equals(ShapeType.Diamond))
concepts.set(Concept.DiamondShape.id(), true);
else
concepts.set(Concept.PrismShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,549 | 24.357143 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/HexagonOnTri.java | package game.functions.graph.generators.basis.tri;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a hexagonal board on a triangular tiling.
*
* @author cambolbro
*/
@Hide
public class HexagonOnTri extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tri.
*
* @param dim The dimension.
*/
public HexagonOnTri
(
final DimFunction dim
)
{
this.basis = BasisType.Triangular;
this.shape = ShapeType.Hexagon;
this.dim = new int[]{ dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int d = dim[0] + (siteType == SiteType.Cell ? 1 : 0);
final int rows = 2 * d - 1;
final int cols = 2 * d - 1;
// // Create vertices
// final List<double[]> vertexList = new ArrayList<double[]>();
// for (int r = 0; r < rows; r++)
// for (int c = 0; c < cols; c++)
// {
// if (c > cols / 2 + r || r - c > cols / 2)
// continue;
// final Point2D pt = Tri.xy(r, c);
// vertexList.add(new double[]{ pt.getX(), pt.getY() });
// }
//
// final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
final Graph graph = new Graph();
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
if (col > cols / 2 + row || row - col > cols / 2)
continue;
graph.addVertex(Tri.xy(row, col));
}
// Edges along rows (bottom half)
int vid = 0;
for (int n = 0; n <= rows / 2; n++)
{
for (int col = 0; col < cols / 2 + n; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + 1));
vid++;
}
vid++;
}
// Edges along rows (top half)
for (int n = 0; n < rows / 2; n++)
{
for (int col = 0; col < cols - 2 - n; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + 1));
vid++;
}
vid++;
}
// Edges between rows (bottom half)
vid = 0;
for (int n = 0; n < rows / 2; n++)
{
final int off = rows / 2 + 1 + n;
for (int col = 0; col < cols / 2 + 1 + n; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + off));
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid + off + 1));
vid++;
}
}
vid += cols;
// Edges between rows (top half)
for (int n = 0; n < rows / 2; n++)
{
final int off = rows - n;
for (int col = 0; col < cols - 1 - n; col++)
{
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid - off));
graph.addEdge(graph.vertices().get(vid), graph.vertices().get(vid - off + 1));
vid++;
}
}
graph.makeFaces(false);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.TriangleTiling.id(), true);
concepts.set(Concept.HexShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,913 | 23.160494 | 100 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/RectangleOnTri.java | package game.functions.graph.generators.basis.tri;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangle shaped board with a hexagonal tiling.
*
* @author cambolbro
*/
@Hide
public class RectangleOnTri extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tri.
*
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
public RectangleOnTri
(
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
final int rows = dimA.eval();
final int cols = (dimB != null) ? dimB.eval() : rows;
this.basis = BasisType.Triangular;
this.shape = (rows == cols) ? ShapeType.Square : ShapeType.Rectangle;
this.dim = new int[]{ rows, cols };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0] + (siteType == SiteType.Cell ? 1 : 0);
final int cols = dim[1] + (siteType == SiteType.Cell ? 1 : 0);
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols + rows; c++)
{
if (c < (r + 1) / 2 || c >= cols + r / 2)
continue;
final Point2D pt = Tri.xy(r, c);
vertexList.add(new double[]{ pt.getX(), pt.getY() });
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// ...
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.TriangleTiling.id(), true);
if (shape.equals(ShapeType.Square))
concepts.set(Concept.SquareShape.id(), true);
else
concepts.set(Concept.RectangleShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,874 | 24.442478 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/StarOnTri.java | package game.functions.graph.generators.basis.tri;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a six-pointed star board on a triangular grid.
*
* @author cambolbro
*/
@Hide
public class StarOnTri extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tri.
*
* @param dim The dimension.
*/
public StarOnTri
(
final DimFunction dim
)
{
this.basis = BasisType.Triangular;
this.shape = ShapeType.Star;
this.dim = new int[] { dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int d = dim[0];
final int rows = 4 * dim[0] + 1;
final int cols = 4 * dim[0] + 1;
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r < d)
{
if (c < d || c - r > d)
continue;
}
else if (r <= 2 * d)
{
if (r - c > d || c >= cols - d)
continue;
}
else if (r <= 3 * d)
{
if (c < d || c - r > d)
continue;
}
else
{
if (c > 3 * d || r - c > d)
continue;
}
final Point2D pt = Tri.xy(r, c);
vertexList.add(new double[] { pt.getX(), pt.getY() });
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, BaseGraphFunction.unit, basis,
shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.TriangleTiling.id(), true);
concepts.set(Concept.StarShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,781 | 21.435484 | 108 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/Tri.java | package game.functions.graph.generators.basis.tri;
import java.awt.geom.Point2D;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimConstant;
import game.functions.dim.DimFunction;
import game.functions.dim.math.Add;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board on a triangular tiling.
*
* @author cambolbro
*/
@SuppressWarnings("javadoc")
public class Tri extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* For defining a tri tiling with two dimensions.
*
* @param shape Board shape [Triangle].
* @param dimA Board dimension; cells or vertices per side.
* @param dimB Board dimension; cells or vertices per side.
*
* @example (tri 8)
* @example (tri Hexagon 3)
*/
public static GraphFunction construct
(
@Opt final TriShapeType shape,
final DimFunction dimA,
@Opt final DimFunction dimB
// @Opt @Name final Boolean pyramidal
)
{
final TriShapeType st = (shape == null) ? TriShapeType.Triangle : shape;
switch (st)
{
case Hexagon:
return new HexagonOnTri(dimA);
case Triangle:
return new TriangleOnTri(dimA);
case Diamond:
return new DiamondOnTri(dimA, null);
case Prism:
return new DiamondOnTri(dimA, (dimB != null ? dimB : dimA));
case Square:
return new RectangleOnTri(dimA, dimA);
case Rectangle:
return new RectangleOnTri(dimA, (dimB != null ? dimB : dimA));
case Star:
return new StarOnTri(dimA);
case Limping:
final DimFunction dimAplus1 = new Add(dimA,new DimConstant(1));
return new CustomOnTri(new DimFunction[] { dimA, dimAplus1 } );
//$CASES-OMITTED$
default:
throw new IllegalArgumentException("Shape " + st + " not supported for hex tiling.");
}
}
/**
* For defining a tri tiling with a polygon or the number of sides.
*
* @param poly Points defining the board shape.
* @param sides Side lengths around board in clockwise order.
*
* @example (tri (poly { {1 2} {1 6} {3 6} {3 4} } ))
* @example (tri { 4 3 -1 2 3 })
*/
public static GraphFunction construct
(
@Or final Poly poly,
@Or final DimFunction[] sides
)
{
int numNonNull = 0;
if (poly != null)
numNonNull++;
if (sides != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Exactly one array parameter must be non-null.");
if (poly != null)
return new CustomOnTri(poly.polygon());
else
return new CustomOnTri(sides);
}
//-------------------------------------------------------------------------
private Tri()
{
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
// Null placeholder to make the grammar recognise Tri
return null;
}
//-------------------------------------------------------------------------
/**
* @param row The row.
* @param col The column.
* @return The Point2D.
*/
public static Point2D xy(final int row, final int col)
{
final double hx = unit;
final double hy = Math.sqrt(3) / 2.0;
return new Point2D.Double(hx * (col - 0.5 * row), hy * row);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 3,901 | 24.337662 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/TriShapeType.java | package game.functions.graph.generators.basis.tri;
/**
* Defines known shapes for the triangular tiling.
*
* @author cambolbro
*/
public enum TriShapeType
{
/** No shape; custom graph. */
NoShape,
/** Square board shape. */
Square,
/** Rectangular board shape. */
Rectangle,
/** Diamond board shape. */
Diamond,
/** Triangular board shape. */
Triangle,
/** Hexagonal board shape. */
Hexagon,
// /** Cross board shape. */
// Cross,
//
// /** Rhombus board shape. */
// Rhombus,
//
// /** Wheel board shape. */
// Wheel,
//
// /** Spiral board shape. */
// Spiral,
//
// /** Shape is derived from another graph. */
// Dual,
//
// /** Wedge shape of height N with 1 vertex at the top and 3 vertices on the bottom, for Alquerque boards. */
// Wedge,
/** Multi-pointed star shape. */
Star,
/** Alternating sides are staggered. */
Limping,
/** Diamond shape extended vertically. */
Prism,
;
}
| 945 | 15.892857 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/TriangleOnTri.java | package game.functions.graph.generators.basis.tri;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Hide;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangle shaped board with a hexagonal tiling.
*
* @author cambolbro
*/
@Hide
public class TriangleOnTri extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Hidden constructor, is a helper for Tri.
*
* @param dim The dimension.
*/
public TriangleOnTri(final DimFunction dim)
{
this.basis = BasisType.Triangular;
this.shape = ShapeType.Triangle;
this.dim = new int[]{ dim.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0] + (siteType == SiteType.Cell ? 1 : 0);
final int cols = dim[0] + (siteType == SiteType.Cell ? 1 : 0);
// Create vertices
final List<double[]> vertexList = new ArrayList<double[]>();
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
{
if (r > c)
continue;
final Point2D pt = Tri.xy(r, c);
vertexList.add(new double[] { pt.getX(), pt.getY() });
}
final Graph graph = BaseGraphFunction.createGraphFromVertexList(vertexList, unit, basis, shape);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.TriangleTiling.id(), true);
concepts.set(Concept.TriangleShape.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 2,516 | 23.920792 | 98 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/basis/tri/package-info.java | /**
* This section contains the boards based on a triangular tiling.
*
*/
package game.functions.graph.generators.basis.tri;
| 129 | 20.666667 | 65 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/Rectangle.java | package game.functions.graph.generators.shape;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.functions.graph.generators.basis.square.DiagonalsType;
import game.functions.graph.generators.basis.square.RectangleOnSquare;
//-----------------------------------------------------------------------------
/**
* Defines a rectangular board.
*
* @author cambolbro
*
*/
@SuppressWarnings("javadoc")
public class Rectangle extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param dimA Number of rows.
* @param dimB Number of columns.
* @param diagonals Which type of diagonals to create, if any.
*
* @example (rectangle 4 6)
*/
public static GraphFunction construct
(
final DimFunction dimA,
@Opt final DimFunction dimB,
@Opt @Name final DiagonalsType diagonals
)
{
return new RectangleOnSquare(dimA, (dimB == null ? dimA : dimB), diagonals, null);
}
//-------------------------------------------------------------------------
private Rectangle()
{
//super(null, null, null, null); //TilingType.Square, ShapeType.NoShape, Integer.valueOf(0), null);
this.basis = null;
this.shape = null;
this.dim = null; //new int[] { rows.eval(), columns == null ? rows.eval() : columns.eval() };
// Ensure that compiler does not pick up default constructor
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 1,875 | 24.69863 | 102 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/Regular.java | package game.functions.graph.generators.shape;
import java.util.BitSet;
import annotations.Hide;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
/**
* Defines a regular polygon.
*
* @author cambolbro
*
* If the Star shape is specified, then edges are created to form points at
* each vertex, rather than joining the vertices around the perimeter.
*/
public class Regular extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param star Whether to make a star shape.
* @param numSides Number of sides.
*
* @example (regular 3)
*/
public Regular
(
@Opt final ShapeStarType star,
final DimFunction numSides
)
{
this.basis = BasisType.NoBasis;
this.shape = (star != null) ? ShapeType.Star : ShapeType.Polygon;
this.dim = new int[] { numSides.eval() };
}
/**
* @param basis The basis.
* @param shape The shape.
* @param dimA The dimension A.
* @param dimB The dimension B.
*/
@Hide
public Regular
(
final BasisType basis,
final ShapeType shape,
final DimFunction dimA,
@Opt final DimFunction dimB
)
{
this.basis = basis;
this.shape = shape;
if (dimB == null)
this.dim = new int[]{ dimA.eval() };
else
this.dim = new int[]{ dimA.eval(), dimB.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int numSides = dim[0];
final double r = numSides / (2 * Math.PI);
final Graph graph = new Graph();
final double offset = (numSides == 4) ? Math.PI / 4 : Math.PI / 2;
for (int n = 0; n < numSides; n++)
{
final double theta = offset + (double)n / numSides * 2 * Math.PI;
final double x = r * Math.cos(theta);
final double y = r * Math.sin(theta);
graph.addVertex(x, y);
}
if (shape == ShapeType.Star)
{
// Simple star
for (int n = 0; n < numSides; n++)
graph.addEdge(n, (n + (numSides - 1) / 2) % numSides);
}
else
{
// Simple polygon
for (int n = 0; n < numSides; n++)
graph.addEdge(n, (n + 1) % numSides);
}
if (siteType == SiteType.Cell)
graph.makeFaces(true);
graph.reorder();
// System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 3,144 | 20.840278 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/Repeat.java | package game.functions.graph.generators.shape;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import annotations.Name;
import annotations.Or;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.types.board.BasisType;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import game.util.graph.Poly;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Repeats specified shape(s) to define the board tiling.
*
* @author cambolbro
*/
public class Repeat extends BaseGraphFunction //implements Serializable
{
private static final long serialVersionUID = 1L;
private final int rows;
private final int columns;
private final Point2D stepColumn;
private final Point2D stepRow;
private List<Polygon> polygons = new ArrayList<Polygon>();
//-------------------------------------------------------------------------
/**
* @param rows Number of rows to repeat.
* @param columns Number of columns to repeat.
* @param step Vectors defining steps to the next column and row.
* @param poly The shape to repeat.
* @param polys The set of shapes to repeat.
*
* @example (repeat 3 4 step:{{-.5 .75} {1 0}} (poly {{0 0} {0 1} {1 1} {1 0}}))
*/
public Repeat
(
final DimFunction rows,
final DimFunction columns,
@Name final Float[][] step,
@Or final Poly poly,
@Or final Poly[] polys
)
{
this.basis = BasisType.NoBasis;
this.shape = ShapeType.NoShape;
this.rows = rows.eval();
this.columns = columns.eval();
if (step.length < 2 || step[0].length < 2 || step[1].length < 2)
{
System.out.println("** Repeat: Step should contain two pairs of values.");
this.stepColumn = new Point2D.Double(1, 0);
this.stepRow = new Point2D.Double(0, 1);
}
else
{
this.stepColumn = new Point2D.Double(step[0][0].floatValue(), step[0][1].floatValue());
this.stepRow = new Point2D.Double(step[1][0].floatValue(), step[1][1].floatValue());
}
if (poly != null)
{
polygons.add(poly.polygon());
}
else
{
for (final Poly ply : polys)
polygons.add(ply.polygon());
}
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final Graph graph = new Graph();
for (int row = 0; row < rows; row++)
for (int col = 0; col < columns; col++)
{
final Point2D ptRef = new Point2D.Double
(
col * stepColumn.getX() + row * stepRow.getX(),
col * stepColumn.getY() + row * stepRow.getY()
);
for (final Polygon polygon : polygons)
{
// final Point2D ptL = polygon.points().get(polygon.points().size() - 1);
// Vertex prev = graph.findOrAddVertex(ptRef.getX() + ptL.getX(), ptRef.getY() + ptL.getY());
//
// for (final Point2D pt : polygon.points())
// {
// final Vertex next = graph.findOrAddVertex(ptRef.getX() + pt.getX(), ptRef.getY() + pt.getY());
// graph.findOrAddEdge(prev, next);
// prev = next;
// }
for (int n = 0; n < polygon.points().size(); n++)
{
final Point2D ptA = polygon.points().get(n);
final Point2D ptB = polygon.points().get((n + 1) % polygon.points().size());
final Vertex vertexA = graph.findOrAddVertex(ptRef.getX() + ptA.getX(), ptRef.getY() + ptA.getY());
final Vertex vertexB = graph.findOrAddVertex(ptRef.getX() + ptB.getX(), ptRef.getY() + ptB.getY());
graph.findOrAddEdge(vertexA, vertexB);
}
}
}
//graph.makeEdges();
graph.makeFaces(false);
graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 4,181 | 26.88 | 105 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/ShapeStarType.java | package game.functions.graph.generators.shape;
/**
* Defines star shape types for known board types.
*
* @author cambolbro
*/
public enum ShapeStarType
{
/** Multi-pointed star shape. */
Star,
;
}
| 209 | 14 | 50 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/Spiral.java | package game.functions.graph.generators.shape;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.Vector;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board based on a spiral tiling, e.g. the Mehen board.
*
* @author cambolbro
*/
public class Spiral extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param turns Number of turns of the spiral.
* @param sites Number of sites to generate in total.
* @param clockwise Whether the spiral should turn clockwise or not [True].
*
* @example (spiral turns:4 sites:80)
*/
public Spiral
(
@Name final DimFunction turns,
@Name final DimFunction sites,
@Opt @Name Boolean clockwise
)
{
this.basis = BasisType.Spiral;
this.shape = ShapeType.Spiral;
final int dirn = (clockwise == null) ? 1 : (clockwise.booleanValue() ? 1 : 0);
this.dim = new int[] { turns.eval(), sites.eval(), dirn };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int numTurns = dim[0];
final int numSites = dim[1];
final boolean clockwise = dim[2] != 0;
if (numSites > 1000)
throw new IllegalArgumentException(numSites + " sites in spiral exceeds limit of 1000.");
final Graph graph = new Graph();
// Create vertices
final double a = 0;
final double b = 1; //numTurns;
final double x0 = 0;
final double y0 = 0;
final Vertex pivot = graph.addVertex(0, 0); // start with central vertex
// Twice the number of vertices per ring, offset between rings
final int base = baseNumber(numTurns, numSites);
final double[] thetas = new double[4 * numSites];
int index = 1;
int steps = base; // number of steps per ring
for (int ring = 1; ring <= numTurns + 1; ring++)
{
final double dTheta = Math.PI * 2 / steps;
double theta = Math.PI * 2 * ring;
if (ring <= 2 || ring % 2 == 1)
theta -= dTheta / 2; // offset so that lines don't coincide between rings
for (int step = 0; step < steps; step++)
{
thetas[index++] = theta;
theta += dTheta;
}
if (ring <= 2)
steps *= 2;
}
// Smoothing passes to reduce unevenness between steps
for (int vid = 2; vid < numSites; vid++)
thetas[vid] = (thetas[vid-1] + thetas[vid+1]) / 2.0;
for (int vid = 2; vid < numSites; vid++)
thetas[vid] = (thetas[vid-1] + thetas[vid+1]) / 2.0;
thetas[1] -= 0.5 * (thetas[2] - thetas[1]); // fudge to nudge vertex 1 into place
for (int vid = 1; vid < numSites; vid++)
{
final double theta = thetas[vid];
final double r = a + b * theta;
final double x = clockwise ? (x0 - r * Math.cos(theta)) : (x0 + r * Math.cos(theta));
final double y = y0 + r * Math.sin(theta);
graph.addVertex(x, y);
}
// Create edges
for (int vid = 0; vid < graph.vertices().size() - 1; vid++)
{
final Vertex vertexN = graph.vertices().get(vid);
final Vertex vertexO = graph.vertices().get(vid + 1);
final Vertex vertexM = graph.vertices().get(Math.max(0, vid - 1));
final Vertex vertexP = graph.vertices().get(Math.min(graph.vertices().size() - 1, vid + 1));
final Vector tangentN = new Vector
(
vertexO.pt2D().getX() - vertexM.pt2D().getX(),
vertexO.pt2D().getY() - vertexM.pt2D().getY()
);
final Vector tangentO = new Vector
(
vertexP.pt2D().getX() - vertexN.pt2D().getX(),
vertexP.pt2D().getY() - vertexN.pt2D().getY()
);
tangentN.normalise();
tangentO.normalise();
graph.addEdge(vertexN, vertexO, tangentN, tangentO); // set as curved
}
// Set pivot
for (final Vertex vertex : graph.vertices())
vertex.setPivot(pivot);
graph.setBasisAndShape(basis, shape);
// Don't reorder Spiral graphs?
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
/**
* @return Number of cells in the inner ring, doubling with each layer.
*/
private static int baseNumber(final int numTurns, final int numSites)
{
for (int base = 1; base < numSites; base++)
{
// Try this base
int steps = base;
int total = 1;
// System.out.println("~~~~~~~~~~~~~\nbase: " + base);
for (int ring = 1; ring < numTurns; ring++)
{
total += steps;
// System.out.println("-- ring " + ring + " total: " + total);
if (total > numSites)
{
if (ring <= numTurns)
return base - 1;
break;
}
if (ring <= 2)
steps *= 2;
}
}
System.out.println("** Spiral.baseNumber(): Couldn't find base number for spiral.");
return 0;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// ...
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.SpiralTiling.id(), true);
concepts.set(Concept.SpiralShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,775 | 25.135747 | 95 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/Wedge.java | package game.functions.graph.generators.shape;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import main.math.MathRoutines;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a triangular wedge shaped graph, with one vertex at the top and
* three vertices along the bottom.
*
* @author cambolbro
*
* @remarks Wedges can be used to add triangular arms to Alquerque boards.
*/
public class Wedge extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param rows Number of rows.
* @param columns Number of columns.
*
* @example (wedge 3)
*/
public Wedge
(
final DimFunction rows,
@Opt final DimFunction columns
)
{
//super(BasisType.NoBasis, ShapeType.Wedge, rows, columns);
this.basis = BasisType.NoBasis;
this.shape = ShapeType.Wedge;
if (columns == null)
this.dim = new int[]{ rows.eval() };
else
this.dim = new int[]{ rows.eval(), columns.eval() };
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final int rows = dim[0];
final int columns = (dim.length == 1) ? 3 : dim[1];
final Graph graph = new Graph();
// Create vertices
final int mid = rows - 1;
for (int r = 0; r < rows; r++)
{
if (r == 0)
{
// Apex
graph.addVertex(mid, mid);
}
else
{
// Non-apex row
final int left = mid - r;
final int right = mid + r;
for (int c = 0; c < columns; c++)
{
final double t = c / (double)(columns - 1);
final double x = MathRoutines.lerp(t, left, right);
final double y = mid - r;
graph.addVertex(x, y);
}
}
}
// Create edges
for (int r = 0; r < rows; r++)
{
if (r == 0)
{
// Apex
for (int c = 0; c < columns; c++)
graph.addEdge(0, c + 1);
}
else
{
// Non-apex row
final int from = r * columns - columns + 1;
// Edges across
for (int c = 0; c < columns - 1; c++)
graph.addEdge(from + c, from + c + 1);
if (r < rows - 1)
{
// Edges down
for (int c = 0; c < columns; c++)
graph.addEdge(from + c, from + columns + c);
}
}
}
//graph.reorder();
graph.setBasisAndShape(basis, shape);
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.PolygonShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 3,246 | 20.503311 | 79 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/package-info.java | /**
* This section contains different types of board shapes.
*/
package game.functions.graph.generators.shape;
| 113 | 21.8 | 57 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/concentric/Concentric.java | package game.functions.graph.generators.shape.concentric;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.dim.DimFunction;
import game.functions.graph.GraphFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board based on a tiling of concentric shapes.
*
* @author cambolbro
*
* @remarks Morris or Merels boards are examples of square concentric boards.
* Circular tilings are centred around a ``pivot'' point.
* For circular boards defined by a list of cell counts,
* the first count should be 0 (centre point) or 1 (centre cell).
*/
public class Concentric extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @param shape Shape of board rings.
* @param sides Number of sides (for polygonal shapes).
* @param cells Number of cells per circular ring.
* @param rings Number of rings [3].
* @param steps Number of steps for target boards with multiple sites per ring [null].
* @param midpoints Whether to add vertices at edge midpoints [True].
* @param joinMidpoints Whether to join concentric midpoints [True].
* @param joinCorners Whether to join concentric corners [False].
* @param stagger Whether to stagger cells in concentric circular rings [False].
*
* @example (concentric Square rings:3)
* @example (concentric Triangle rings:3 joinMidpoints:False joinCorners:True)
* @example (concentric Hexagon rings:3 joinMidpoints:False joinCorners:True)
* @example (concentric sides:5 rings:3)
*
* @example (concentric { 8 })
* @example (concentric { 0 8 })
* @example (concentric { 1 4 8 } stagger:True)
*
* @example (concentric Target rings:4)
* @example (concentric Target rings:4 steps:16)
*/
@SuppressWarnings("javadoc")
public static GraphFunction construct
(
@Or final ConcentricShapeType shape,
@Or @Name final DimFunction sides,
@Or final DimFunction[] cells,
@Opt @Name final DimFunction rings,
@Opt @Name final DimFunction steps,
@Opt @Name final BooleanFunction midpoints,
@Opt @Name final BooleanFunction joinMidpoints,
@Opt @Name final BooleanFunction joinCorners,
@Opt @Name final BooleanFunction stagger
)
{
int numNonNull = 0;
if (sides != null)
numNonNull++;
if (cells != null)
numNonNull++;
if (numNonNull > 1)
throw new IllegalArgumentException("Only one of 'shape', 'sides' or 'cells' can be non-null.");
if (shape != null && rings != null)
{
// Known shape (including target)
if (shape == ConcentricShapeType.Triangle)
{
return new ConcentricRegular(3, rings.eval(), midpoints, joinMidpoints, joinCorners);
}
else if (shape == ConcentricShapeType.Square)
{
return new ConcentricRegular(4, rings.eval(), midpoints, joinMidpoints, joinCorners);
}
else if (shape == ConcentricShapeType.Hexagon)
{
return new ConcentricRegular(6, rings.eval(), midpoints, joinMidpoints, joinCorners);
}
else if (shape == ConcentricShapeType.Target)
{
// Is a target board
if (steps != null)
{
// Make a wheel board
final int[] cellsPerRing = new int[rings.eval()];
for (int c = 0; c < cellsPerRing.length; c++)
cellsPerRing[c] = steps.eval();
return new ConcentricCircle(cellsPerRing, null);
}
else
{
// Make a target board (one site per cell)
return new ConcentricTarget(rings.eval());
}
}
}
else if (sides != null && rings != null)
{
// Regular polygon
return new ConcentricRegular(sides.eval(), rings.eval(), midpoints, joinMidpoints, joinCorners);
}
else if (cells != null)
{
// Circle (wheel) board
final int[] cellsPerRing = new int[cells.length];
for (int c = 0; c < cells.length; c++)
cellsPerRing[c] = cells[c].eval();
return new ConcentricCircle(cellsPerRing, stagger);
}
// Should never reach this point
throw new IllegalArgumentException("Concentric board must specify sides, cells or rings.");
}
//-------------------------------------------------------------------------
private Concentric()
{
// Ensure that compiler does not pick up default constructor.
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
return null; // null placeholder to make the grammar recognise Concentric
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
//-------------------------------------------------------------------------
}
| 5,137 | 30.716049 | 99 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/concentric/ConcentricCircle.java | package game.functions.graph.generators.shape.concentric;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import annotations.Hide;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import main.math.Vector;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board based on a circular tiling.
*
* @author cambolbro
*
* @remarks Circular tilings are centred around a ``pivot'' point.
* The first ring value should be 0 (centre point) or 1 (centre cell).
*/
@Hide
public class ConcentricCircle extends Basis
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* Sample position for circular graph vertex.
*/
public class Sample
{
/**
* The x coordinate.
*/
public double x;
/**
* The y coordinate.
*/
public double y;
/**
* The theta value.
*/
public double theta;
/**
* @param x The x coordinate.
* @param y The y coordinate.
* @param theta The theta value.
*/
public Sample(final double x, final double y, final double theta)
{
this.x = x;
this.y = y;
this.theta = theta;
}
}
//-------------------------------------------------------------------------
/** Number of cells per concentric ring. */
private final int[] cellsPerRing;
/** Whether to offset cells in adjacent rings relative to each other. */
private final BooleanFunction staggerFn;
private boolean stagger;
//-------------------------------------------------------------------------
/**
* @param cellsPerRing Number of cells per concentric ring.
* @param stagger Whether to stagger cells in adjacent rings [False].
*/
public ConcentricCircle
(
final int[] cellsPerRing,
@Opt @Name final BooleanFunction stagger
)
{
this.basis = BasisType.Concentric;
this.shape = ShapeType.Circle;
this.cellsPerRing = cellsPerRing;
//this.stagger = (stagger == null) ? false : stagger.eval();
this.staggerFn = stagger;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
this.stagger = (staggerFn == null) ? false : staggerFn.eval(context);
final Graph graph = new Graph();
if (siteType == SiteType.Cell)
generateForCells(graph);
else
generateForVertices(graph);
//graph.reorder();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
/**
* @param graph Graph to be generated for playing on the cells.
*/
public void generateForCells(final Graph graph)
{
final int numRings = cellsPerRing.length;
if (numRings < 1)
return;
final Vertex pivot = graph.addVertex(0, 0);
@SuppressWarnings("unchecked")
final List<Sample>[] samples = new ArrayList[numRings + 1];
for (int ring = 0; ring < numRings + 1; ring++)
samples[ring] = new ArrayList<Sample>();
final double ref = Math.PI / 2; // orient to start at top
// System.out.println("numRings=" + numRings);
// Create samples
for (int ring = 0; ring < numRings; ring++)
{
final int cellsThisRing = Math.abs(cellsPerRing[ring]);
final double rI = Math.max(0, ring - 0.5);
final double rO = ring + 0.5;
final double ringOffset = (stagger && ring % 2 == 1)
? 2 * Math.PI / cellsThisRing / 2 // half a cell width
: 0;
if (cellsThisRing < 2)
continue;
for (int step = 0; step < cellsThisRing; step++)
{
double theta = ref + ringOffset - 2 * Math.PI * step / cellsThisRing;
while (theta < -Math.PI)
theta += 2 * Math.PI;
while (theta > Math.PI)
theta -= 2 * Math.PI;
//System.out.println("theta=" + theta);
final double ix = rI * Math.cos(theta);
final double iy = rI * Math.sin(theta);
final double ox = rO * Math.cos(theta);
final double oy = rO * Math.sin(theta);
samples[ring].add(new Sample(ix, iy, theta));
samples[ring + 1].add(new Sample(ox, oy, theta));
}
}
// Order samples by angle within each ring
for (int ring = 0; ring < numRings + 1; ring++)
Collections.sort(samples[ring], new Comparator<Sample>()
{
@Override
public int compare(final Sample a, final Sample b)
{
return (a.theta == b.theta)
? 0
: (a.theta < b.theta) ? -1 : 1;
}
});
// Remove duplicate samples
for (int ring = 0; ring < numRings + 1; ring++)
for (int n = samples[ring].size() - 1; n > 0; n--)
{
final Sample sampleA = samples[ring].get(n);
final Sample sampleB = samples[ring].get((n + samples[ring].size() - 1) % samples[ring].size());
if (MathRoutines.distance(sampleA.x, sampleA.y, sampleB.x, sampleB.y) < tolerance)
samples[ring].remove(n);
}
// Now create vertices
for (int ring = 0; ring < numRings + 1; ring++)
for (final Sample sample : samples[ring])
graph.findOrAddVertex(sample.x, sample.y);
// Create concentric edges around rings (curved)
for (int ring = 0; ring < numRings + 1; ring++)
{
final int ringSize = samples[ring].size();
if (ringSize < 2)
continue; // not enough samples
for (int n = 0; n < ringSize; n++)
{
final Sample sampleA = samples[ring].get(n);
final Sample sampleB = samples[ring].get((n + 1) % ringSize);
final Vertex vertexA = graph.findVertex(sampleA.x, sampleA.y);
final Vertex vertexB = graph.findVertex(sampleB.x, sampleB.y);
if (vertexA.id() == vertexB.id())
continue;
final Sample sampleAA = samples[ring].get((n - 1 + ringSize) % ringSize);
final Sample sampleBB = samples[ring].get((n + 2) % ringSize);
final Vector tangentA = new Vector(sampleB.x - sampleAA.x, sampleB.y - sampleAA.y);
final Vector tangentB = new Vector(sampleA.x - sampleBB.x, sampleA.y - sampleBB.y);
tangentA.normalise();
tangentB.normalise();
graph.findOrAddEdge(vertexA, vertexB, tangentA, tangentB); // set as curved
}
}
// Create perpendicular edges between rings (not curved)
for (int ring = 0; ring < numRings; ring++)
{
final int cellsThisRing = Math.abs(cellsPerRing[ring]);
final double rI = Math.max(0, ring - 0.5);
final double rO = ring + 0.5;
final double ringOffset = (stagger && ring % 2 == 1)
? 2 * Math.PI / cellsThisRing / 2 // half a cell width
: 0;
if (cellsThisRing < 2)
continue;
for (int step = 0; step < cellsThisRing; step++)
{
final double theta = ref + ringOffset - 2 * Math.PI * step / cellsThisRing;
final double ix = rI * Math.cos(theta);
final double iy = rI * Math.sin(theta);
final double ox = rO * Math.cos(theta);
final double oy = rO * Math.sin(theta);
final Vertex vertexA = graph.findOrAddVertex(ix, iy);
final Vertex vertexB = graph.findOrAddVertex(ox, oy);
if (vertexA.id() == vertexB.id())
continue;
graph.findOrAddEdge(vertexA, vertexB);
}
}
// Set pivot
for (final Vertex vertex : graph.vertices())
vertex.setPivot(pivot);
graph.makeFaces(true);
}
//-------------------------------------------------------------------------
/**
* @param graph Graph to be generated for playing on the vertices.
*/
public void generateForVertices(final Graph graph)
{
if (cellsPerRing.length == 0)
return; // nothing to do
if (cellsPerRing.length == 1)
{
// Shape is a simple polygon
simplePolygon(graph);
return;
}
int[] vertsPerRing;
if (Math.abs(cellsPerRing[0]) > 1)
{
// No centre: add a default ring of 0
vertsPerRing = new int[cellsPerRing.length + 1];
vertsPerRing[0] = 0;
for (int r = 0; r < cellsPerRing.length; r++)
vertsPerRing[r + 1] = cellsPerRing[r];
}
else
{
vertsPerRing = new int[cellsPerRing.length];
for (int r = 0; r < cellsPerRing.length; r++)
vertsPerRing[r] = cellsPerRing[r];
}
final boolean noPivot = (vertsPerRing[0] == 0);
final int numRings = vertsPerRing.length;
if (numRings < 1)
return;
//final Vertex pivot = graph.addVertex(0, 0);
@SuppressWarnings("unchecked")
final List<Sample>[] samples = new ArrayList[numRings];
for (int ring = 0; ring < numRings; ring++)
samples[ring] = new ArrayList<Sample>();
// Always have centre vertex
//samples[0].add(new Sample(0, 0, 0));
final double ref = Math.PI / 2; // orient to start at top
// Create samples
for (int ring = 0; ring < numRings; ring++)
{
final int vertsThisRing = Math.abs(vertsPerRing[ring]);
// System.out.println("Ring " + ring + " has " + vertsThisRing + " cells.");
final double r = ring;
final double ringOffset = (stagger && ring % 2 == 1)
? 2 * Math.PI / vertsThisRing / 2 // half a cell width
: 0;
//if (vertsThisRing < 2)
// continue;
for (int step = 0; step < vertsThisRing; step++)
{
final double theta = ref + ringOffset - 2 * Math.PI * step / vertsThisRing;
final double x = r * Math.cos(theta);
final double y = r * Math.sin(theta);
samples[ring].add(new Sample(x, y, theta));
//graph.findOrAddVertex(x, y);
}
}
// Order samples by angle
for (int ring = 1; ring < numRings; ring++)
Collections.sort(samples[ring], new Comparator<Sample>()
{
@Override
public int compare(final Sample a, final Sample b)
{
return (a.theta == b.theta)
? 0
: (a.theta < b.theta) ? -1 : 1;
}
});
// Remove duplicate samples
for (int ring = 1; ring < numRings; ring++)
for (int n = samples[ring].size() - 1; n > 0; n--)
{
final Sample sampleA = samples[ring].get(n);
final Sample sampleB = samples[ring].get((n + samples[ring].size() - 1) % samples[ring].size());
if (MathRoutines.distance(sampleA.x, sampleA.y, sampleB.x, sampleB.y) < 0.1)
samples[ring].remove(n);
}
// Now create vertices
for (int ring = 0; ring < numRings; ring++)
for (final Sample sample : samples[ring])
graph.findOrAddVertex(sample.x, sample.y);
// Create concentric edges around rings (curved)
for (int ring = 1; ring < numRings; ring++)
{
// System.out.println("Ring " + ring + " (" + samples[ring].size() + "):");
if (vertsPerRing[ring] < 2)
continue; // no edges around this ring
final int ringSize = samples[ring].size();
if (ringSize < 2)
continue; // not enough samples anyway
for (int n = 0; n < ringSize; n++)
{
final Sample sampleA = samples[ring].get(n);
final Sample sampleB = samples[ring].get((n + 1) % ringSize);
final Vertex vertexA = graph.findOrAddVertex(sampleA.x, sampleA.y);
final Vertex vertexB = graph.findOrAddVertex(sampleB.x, sampleB.y);
if (vertexA.id() == vertexB.id())
continue;
// System.out.print(" " + vertexA.id() + "-" + vertexB.id());
final Sample sampleAA = samples[ring].get((n - 1 + ringSize) % ringSize);
final Sample sampleBB = samples[ring].get((n + 2) % ringSize);
final Vector tangentA = new Vector(sampleB.x - sampleAA.x, sampleB.y - sampleAA.y);
final Vector tangentB = new Vector(sampleA.x - sampleBB.x, sampleA.y - sampleBB.y);
tangentA.normalise();
tangentB.normalise();
graph.findOrAddEdge(vertexA, vertexB, tangentA, tangentB); // set as curved
}
// System.out.println();
}
// Create perpendicular edges between rings (not curved)
for (int ring = 0; ring < numRings - 1; ring++)
{
for (final Sample sample : samples[ring])
{
// See if vertex on next layer lines up
final Vertex vertexA = graph.findVertex(sample.x, sample.y);
if (vertexA == null)
{
System.out.println("** Couldn't find vertex (" + sample.x + "," + sample.y + ").");
continue;
}
if (ring == 0)
{
// Join to all vertices on ring 1
for (final Sample sampleB : samples[1])
{
final Vertex vertexB = graph.findVertex(sampleB.x, sampleB.y);
if (vertexB != null)
graph.findOrAddEdge(vertexA, vertexB);
}
}
else
{
// Only match vertices in this direction
final double ratio = (ring + 1) / (double)ring;
final double xB = sample.x * ratio;
final double yB = sample.y * ratio;
final Vertex vertexB = graph.findVertex(xB, yB);
if (vertexB != null)
{
graph.findOrAddEdge(vertexA, vertexB);
if (noPivot)
{
// Set inner vertex to be pivot of outer vertex
vertexB.setPivot(vertexA);
}
}
}
}
}
if (vertsPerRing[0] != 0)
{
// Find and set pivot
final Vertex pivot = graph.findVertex(0, 0);
if (pivot == null)
{
System.out.println("** Null pivot in Circle graph.");
return;
}
for (final Vertex vertex : graph.vertices())
vertex.setPivot(pivot);
}
}
//-------------------------------------------------------------------------
private void simplePolygon(final Graph graph)
{
final int numSides = cellsPerRing[0];
if (numSides < 3)
{
System.out.println("** Bad number of circle sides: " + numSides);
}
final double r = numSides / (2 * Math.PI);
final double offset = (numSides == 4) ? Math.PI / 4 : Math.PI / 2;
for (int n = 0; n < numSides; n++)
{
final double theta = offset + (double)n / numSides * 2 * Math.PI;
final double x = r * Math.cos(theta);
final double y = r * Math.sin(theta);
graph.addVertex(x, y);
}
// Simple polygon
for (int n = 0; n < numSides; n++)
graph.addEdge(n, (n + 1) % numSides);
graph.reorder();
// System.out.println(graph);
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.ConcentricTiling.id(), true);
concepts.set(Concept.CircleTiling.id(), true);
concepts.set(Concept.CircleShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 14,879 | 26.054545 | 100 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/concentric/ConcentricRegular.java | package game.functions.graph.generators.shape.concentric;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.booleans.BooleanFunction;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a regular polygonal concentric board.
*
* @author cambolbro
*
* @remarks Morris or Merels boards examples of concentric square boards
* and typically played on the vertices rather than the cells.
*/
@Hide
public class ConcentricRegular extends Basis
{
private static final long serialVersionUID = 1L;
private final int numSides;
private final int numRings;
private final BooleanFunction midpointsFn;
private final BooleanFunction joinMidpointsFn;
private final BooleanFunction joinCornersFn;
//-------------------------------------------------------------------------
/**
* @param sides Number of sides per ring.
* @param rings Number of rings [3].
* @param midpoints Whether to generate a midpoint for each side [True].
* @param joinMidpoints Whether to join midpoints in adjacent rings [True].
* @param joinCorners Whether to join corners [False].
*/
public ConcentricRegular
(
final int sides,
final int rings,
final BooleanFunction midpoints,
final BooleanFunction joinMidpoints,
final BooleanFunction joinCorners
)
{
this.basis = BasisType.Concentric;
// Check number of sides, in case users uses sides:4 instead of Square
switch (sides)
{
case 3: this.shape = ShapeType.Triangle; break;
case 4: this.shape = ShapeType.Square; break;
case 6: this.shape = ShapeType.Hexagon; break;
default: this.shape = ShapeType.Regular; break;
}
this.numSides = sides;
this.numRings = rings;
this.midpointsFn = midpoints;
this.joinMidpointsFn = joinMidpoints;
this.joinCornersFn = joinCorners;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (numSides < 3)
throw new IllegalArgumentException("Concentric board shape must have at least three sides.");
final Graph graph = new Graph();
if (numRings < 1)
return graph;
final boolean midpoints = (midpointsFn != null) ? midpointsFn.eval(context) : true;
final boolean joinMidpoints = (joinMidpointsFn != null) ? joinMidpointsFn.eval(context) : true;
final boolean joinCorners = (joinCornersFn != null) ? joinCornersFn.eval(context) : false;
final double arc = 2 * Math.PI / numSides;
final double ref = Math.PI / 2 + (numSides % 2 == 0 ? arc / 2 : 0); // starting theta
// Create vertices and edges along each rings
int baseV = 0;
for (int ring = 0; ring < numRings; ring++)
{
final double radius = 1 + ring * (numSides == 3 ? 2 : 1);
// Create vertices along this ring
for (int side = 0; side < numSides; side++)
{
final double xa = radius * Math.cos(ref + arc * side);
final double ya = radius * Math.sin(ref + arc * side);
final double xc = radius * Math.cos(ref + arc * (side + 1));
final double yc = radius * Math.sin(ref + arc * (side + 1));
final double xb = (xa + xc) / 2.0;
final double yb = (ya + yc) / 2.0;
graph.findOrAddVertex(xa, ya);
if (midpoints)
graph.findOrAddVertex(xb, yb);
}
// Create edges along this ring
for (int v = baseV; v < graph.vertices().size(); v++)
{
final int vv = (v < graph.vertices().size() - 1) ? v + 1 : baseV;
graph.addEdge(v, vv);
}
baseV = graph.vertices().size();
}
// Create edges between rings
if (midpoints && joinMidpoints || joinCorners)
{
final int edgesPerSide = midpoints ? 2 : 1;
final int edgesPerRing = numSides * edgesPerSide;
for (int ring = 0; ring < numRings - 1; ring++)
{
for (int side = 0; side < numSides; side++)
{
if (joinCorners)
{
// Corner vertex
final int v = ring * edgesPerRing + side * edgesPerSide;
final int vv = v + edgesPerRing;
graph.addEdge(v, vv);
}
if (joinMidpoints)
{
// Midpoint vertex
final int v = ring * edgesPerRing + side * edgesPerSide + 1;
final int vv = v + edgesPerRing;
graph.addEdge(v, vv);
}
}
}
}
graph.setBasisAndShape(basis, shape);
graph.reorder();
if (siteType == SiteType.Cell)
graph.makeFaces(true);
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.ConcentricTiling.id(), true);
concepts.set(Concept.MorrisTiling.id(), true);
concepts.set(Concept.RegularShape.id(), true);
concepts.set(Concept.PolygonShape.id(), true);
switch (numSides)
{
case 3: concepts.set(Concept.TriangleShape.id(), true); break;
case 4: concepts.set(Concept.SquareShape.id(), true); break;
case 6: concepts.set(Concept.HexShape.id(), true); break;
default: concepts.set(Concept.RegularShape.id(), true); break;
}
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,660 | 26.8867 | 97 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/concentric/ConcentricShapeType.java | package game.functions.graph.generators.shape.concentric;
/**
* Defines star shape types for known board types.
*
* @author cambolbro
*/
public enum ConcentricShapeType
{
/** Concentric squares rings, e.g. Morris boards. */
Square,
/** Concentric triangles. */
Triangle,
/** Concentric hexagons. */
Hexagon,
/** Concentric circles, like a target. */
Target,
;
}
| 386 | 15.826087 | 57 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/concentric/ConcentricTarget.java | package game.functions.graph.generators.shape.concentric;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.graph.generators.basis.Basis;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Face;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.Vector;
import other.concept.Concept;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Defines a board formed by a set of concentric rings.
*
* @author cambolbro
*
* @remarks Target boards are played on the cells only.
*/
@Hide
public class ConcentricTarget extends Basis
{
private static final long serialVersionUID = 1L;
/** Number of concentric rings. */
private final int numRings;
//-------------------------------------------------------------------------
/**
* @param rings Number of concentric rings.
*/
public ConcentricTarget
(
final int rings
)
{
this.basis = BasisType.Concentric;
this.shape = ShapeType.Circle;
this.numRings = rings;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
final Graph graph = new Graph();
if (numRings < 1)
return graph;
if (siteType != SiteType.Cell)
{
throw new IllegalArgumentException("Concentric target board must use cells only.");
}
// final Vertex pivot = graph.addVertex(0, 0);
// @SuppressWarnings("unchecked")
// final List<Sample>[] samples = new ArrayList[numRings + 1];
// for (int ring = 0; ring < numRings + 1; ring++)
// samples[ring] = new ArrayList<Sample>();
//
// final double ref = Math.PI / 2; // orient to start at top
//
//// System.out.println("numRings=" + numRings);
//
// // Create samples
// for (int ring = 0; ring < numRings; ring++)
// {
// final int cellsThisRing = Math.abs(cellsPerRing[ring]);
//
// final double rI = Math.max(0, ring - 0.5);
// final double rO = ring + 0.5;
//
// final double ringOffset = (stagger && ring % 2 == 1)
// ? 2 * Math.PI / cellsThisRing / 2 // half a cell width
// : 0;
// if (cellsThisRing < 2)
// continue;
//
// for (int step = 0; step < cellsThisRing; step++)
// {
// double theta = ref + ringOffset - 2 * Math.PI * step / cellsThisRing;
//
// while (theta < -Math.PI)
// theta += 2 * Math.PI;
//
// while (theta > Math.PI)
// theta -= 2 * Math.PI;
//
// //System.out.println("theta=" + theta);
//
// final double ix = rI * Math.cos(theta);
// final double iy = rI * Math.sin(theta);
// final double ox = rO * Math.cos(theta);
// final double oy = rO * Math.sin(theta);
//
// samples[ring].add(new Sample(ix, iy, theta));
// samples[ring + 1].add(new Sample(ox, oy, theta));
// }
// }
//
// // Order samples by angle within each ring
// for (int ring = 0; ring < numRings + 1; ring++)
// Collections.sort(samples[ring], new Comparator<Sample>()
// {
// @Override
// public int compare(final Sample a, final Sample b)
// {
// return (a.theta == b.theta)
// ? 0
// : (a.theta < b.theta) ? -1 : 1;
// }
// });
//
// // Remove duplicate samples
// for (int ring = 0; ring < numRings + 1; ring++)
// for (int n = samples[ring].size() - 1; n > 0; n--)
// {
// final Sample sampleA = samples[ring].get(n);
// final Sample sampleB = samples[ring].get((n + samples[ring].size() - 1) % samples[ring].size());
//
// if (MathRoutines.distance(sampleA.x, sampleA.y, sampleB.x, sampleB.y) < tolerance)
// samples[ring].remove(n);
// }
// Each ring
final int numSteps = 8;
final double arc = 2 * Math.PI / numSteps;
final double off = Math.PI / 2;
for (int ring = 0; ring < numRings; ring++)
{
final double radius = ring + 1;
final int baseV = graph.vertices().size();
// Create vertices around this ring
for (int step = 0; step < numSteps; step++)
{
final double x = radius * Math.cos(off + arc * step);
final double y = radius * Math.sin(off + arc * step);
graph.findOrAddVertex(x, y);
}
// Create edges around this ring
for (int va = baseV; va < graph.vertices().size(); va++)
{
final int vb = (va < graph.vertices().size() - 1) ? va + 1 : baseV;
final Vertex vertexA = graph.vertices().get(va);
final Vertex vertexB = graph.vertices().get(vb);
final Vector tangentA = new Vector(vertexA.pt2D());
tangentA.normalise();
tangentA.perpendicular();
final Vector tangentB = new Vector(vertexB.pt2D());
tangentB.normalise();
tangentB.perpendicular();
tangentB.reverse();
graph.addEdge(vertexA, vertexB, tangentA, tangentB);
}
// Manually create face for this ring here?
}
graph.makeFaces(true);
// Reposition each face's reference point to avoid overlap
for (int f = 0; f < graph.faces().size(); f++)
{
final Face face = graph.faces().get(f);
final double y = (f == 0) ? 0 : -f - 0.5;
face.setPt(0, y, 0);
}
return graph;
}
//-------------------------------------------------------------------------
@Override
public long gameFlags(Game game)
{
return 0;
}
@Override
public void preprocess(Game game)
{
// Nothing to do.
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.set(Concept.ConcentricTiling.id(), true);
concepts.set(Concept.TargetShape.id(), true);
return concepts;
}
//-------------------------------------------------------------------------
}
| 5,810 | 25.294118 | 102 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/generators/shape/concentric/package-info.java | /**
* This section contains boards based on tilings of concentric shapes.
*
*/
package game.functions.graph.generators.shape.concentric;
| 141 | 22.666667 | 70 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Add.java | package game.functions.graph.operators;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.floats.FloatFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.GraphElement;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import main.math.Point3D;
import main.math.Vector;
import other.context.Context;
/**
* Adds elements to a graph.
*
* @author cambolbro
*
* @remarks The elements to be added can be vertices, edges or faces.
* Edges and faces will create the specified vertices if they don't already exist.
* When defining curved edges, the first and second set of numbers are the
* end points locations and the third and fourth set of numbers are the
* tangent directions for the edge end points.
*/
public final class Add extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
private final FloatFunction[][] vertexFns;
private final FloatFunction[][][] edgeFns;
private final FloatFunction[][][] edgeCurvedFns;
private final FloatFunction[][][] faceFns;
private final DimFunction[][] edgeIndexFns;
private final DimFunction[][] faceIndexFns;
private final boolean connect;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graph The graph to remove elements from.
* @param vertices Locations of vertices to add.
* @param edges Locations of end points of edges to add.
* @param Edges Indices of end point vertices to add.
* @param edgesCurved Locations of end points and tangents of edges to add.
* @param cells Locations of vertices of faces to add.
* @param Cells Indices of vertices of faces to add.
* @param connect Whether to connect newly added vertices to nearby neighbours [False].
*
* @example (add (square 4) vertices:{ {1 2} })
* @example (add edges:{ {{0 0} {1 1}} })
* @example (add (square 4) cells:{ {{1 1} {1 2} {3 2} {3 1}} })
* @example (add (square 2) edgesCurved:{ {{0 0} {1 0} {1 2} {-1 2}} })
*/
public Add
(
@Opt final GraphFunction graph,
@Opt @Name final FloatFunction[][] vertices,
@Opt @Or @Name final FloatFunction[][][] edges,
@Opt @Or @Name final DimFunction[][] Edges,
@Opt @Name final FloatFunction[][][] edgesCurved,
@Opt @Or @Name final FloatFunction[][][] cells,
@Opt @Or @Name final DimFunction[][] Cells,
@Opt @Name final Boolean connect
)
{
int numNonNullE = 0;
if (edges != null)
numNonNullE++;
if (Edges != null)
numNonNullE++;
if (numNonNullE > 1)
throw new IllegalArgumentException("Only one 'edge' parameter can be non-null.");
int numNonNullF = 0;
if (cells != null)
numNonNullF++;
if (Cells != null)
numNonNullF++;
if (numNonNullF > 1)
throw new IllegalArgumentException("Only one 'face' parameter can be non-null.");
graphFn = graph;
vertexFns = vertices;
edgeFns = edges;
faceFns = cells;
edgeCurvedFns = edgesCurved;
edgeIndexFns = Edges;
faceIndexFns = Cells;
this.connect = (connect == null) ? false : connect.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = (graphFn == null) ? new Graph() : graphFn.eval(context, siteType);
// Note: Retain the tiling and shape of the original elements.
// Load specified vertices
final List<Point3D> vertices = new ArrayList<Point3D>();
if (vertexFns != null)
{
for (int v = 0; v < vertexFns.length; v++)
{
final FloatFunction[] fns = vertexFns[v];
if (fns.length < 2)
{
System.out.println("** Add.eval(): Two or three values expected for vertex " + v + ".");
continue;
}
final double x = fns[0].eval(context);
final double y = fns[1].eval(context);
final double z = (fns.length > 2) ? fns[2].eval(context) : 0;
vertices.add(new Point3D(x, y, z));
}
}
// Load specified edges
final List<List<Point3D>> edges = new ArrayList<List<Point3D>>();
if (edgeFns != null)
{
for (int e = 0; e < edgeFns.length; e++)
{
final FloatFunction[][] fns = edgeFns[e];
if (fns.length != 2)
{
System.out.println("** Add.eval(): Two vertex definitions expected for edge " + e + ".");
continue;
}
if (fns[0].length < 2)
{
System.out.println("** Add.eval(): Two values expcted for vertex A for edge " + e + ".");
continue;
}
if (fns[1].length < 2)
{
System.out.println("** Add.eval(): Two values expcted for vertex B for edge " + e + ".");
continue;
}
final double ax = fns[0][0].eval(context);
final double ay = fns[0][1].eval(context);
final double az = (fns[0].length > 2) ? fns[0][2].eval(context) : 0;
final double bx = fns[1][0].eval(context);
final double by = fns[1][1].eval(context);
final double bz = (fns[1].length > 2) ? fns[1][2].eval(context) : 0;
final List<Point3D> vertexPair = new ArrayList<Point3D>();
vertexPair.add(new Point3D(ax, ay, az));
vertexPair.add(new Point3D(bx, by, bz));
edges.add(vertexPair);
}
}
// Load specified curved edges
if (edgeCurvedFns != null)
{
for (int e = 0; e < edgeCurvedFns.length; e++)
{
final FloatFunction[][] fns = edgeCurvedFns[e];
if (fns.length != 4)
{
System.out.println("** Add.eval(): Four points expected for curved edge " + e + ".");
continue;
}
if (fns[0].length < 2)
{
System.out.println("** Add.eval(): Two values expcted for vertex A for edge " + e + ".");
continue;
}
if (fns[1].length < 2)
{
System.out.println("** Add.eval(): Two or three values expcted for vertex B for edge " + e + ".");
continue;
}
if (fns[2].length != 2)
{
System.out.println("** Add.eval(): Two or three values expcted for tangent A for edge " + e + ".");
continue;
}
if (fns[3].length != 2)
{
System.out.println("** Add.eval(): Two values expcted for tangent B for edge " + e + ".");
continue;
}
final double ax = fns[0][0].eval(context);
final double ay = fns[0][1].eval(context);
final double az = (fns[0].length > 2) ? fns[0][2].eval(context) : 0;
final double bx = fns[1][0].eval(context);
final double by = fns[1][1].eval(context);
final double bz = (fns[1].length > 2) ? fns[1][2].eval(context) : 0;
final double tax = fns[2][0].eval(context);
final double tay = fns[2][1].eval(context);
final double tbx = fns[3][0].eval(context);
final double tby = fns[3][1].eval(context);
final Vector tangentA = new Vector(tax, tay);
final Vector tangentB = new Vector(tbx, tby);
// Don't normalise vectors! Allow arbitrary lengths for better control
//tangentA.normalise();
//tangentB.normalise();
final Vertex vertexA = graph.findOrAddVertex(ax, ay, az);
final Vertex vertexB = graph.findOrAddVertex(bx, by, bz);
graph.addEdge(vertexA, vertexB, tangentA, tangentB);
}
}
// Load specified faces
final List<List<Point3D>> faces = new ArrayList<List<Point3D>>();
if (faceFns != null)
{
for (int f = 0; f < faceFns.length; f++)
{
final FloatFunction[][] fns = faceFns[f];
// if (fns.length < 6)
// {
// System.out.println("** Add.eval(): At least six values expected for face " + f + ".");
// }
final List<Point3D> face = new ArrayList<Point3D>();
for (int v = 0; v < fns.length; v++)
{
final double x = fns[v][0].eval(context);
final double y = fns[v][1].eval(context);
final double z = (fns[v].length > 2) ? fns[v][2].eval(context) : 0;
face.add(new Point3D(x, y, z));
}
faces.add(face);
}
}
// Add vertices
final List<Vertex> newVertices = new ArrayList<Vertex>();
for (final Point3D pt : vertices)
{
final Vertex vertex = graph.findVertex(pt);
if (vertex != null)
{
System.out.println("** Duplicate vertex found - not adding.");
}
else
{
newVertices.add(graph.addVertex(pt));
}
}
// Add edges
for (final List<Point3D> edgePts : edges)
{
final Point3D ptA = edgePts.get(0);
final Point3D ptB = edgePts.get(1);
// Find or create first vertex
Vertex vertexA = graph.findVertex(ptA);
if (vertexA == null)
{
graph.addVertex(ptA);
vertexA = graph.vertices().get(graph.vertices().size() - 1);
}
// Find or create second vertex
Vertex vertexB = graph.findVertex(ptB);
if (vertexB == null)
{
graph.addVertex(ptB);
vertexB = graph.vertices().get(graph.vertices().size() - 1);
}
graph.findOrAddEdge(vertexA.id(), vertexB.id());
}
// Add faces
for (final List<Point3D> facePts : faces)
{
// Determine vertex ids
final int[] vertIds = new int[facePts.size()];
// Pass 1: Create vertices if needed
for (int n = 0; n < facePts.size(); n++)
{
// Find or create vertex
final Point3D pt = facePts.get(n);
Vertex vertex = graph.findVertex(pt);
if (vertex == null)
{
graph.addVertex(pt);
vertex = graph.vertices().get(graph.vertices().size() - 1);
}
vertIds[n] = vertex.id();
}
// Pass 2: Create edges if needed
for (int n = 0; n < vertIds.length; n++)
{
final int vidA = vertIds[n];
final int vidB = vertIds[(n + 1) % vertIds.length];
final Edge edge = graph.findEdge(vidA, vidB);
if (edge == null)
graph.findOrAddEdge(vidA, vidB);
}
graph.findOrAddFace(vertIds);
}
// Now check for edge and face additions by index, after graph has been created
if (edgeIndexFns != null)
{
// Add edges by vertex index pairs
for (int e = 0; e < edgeIndexFns.length; e++)
{
if (edgeIndexFns[e].length < 2)
{
System.out.println("** Add.eval(): Edge index pair does not have two entries.");
continue;
}
final int aid = edgeIndexFns[e][0].eval();
final int bid = edgeIndexFns[e][1].eval();
if (aid >= graph.vertices().size() || bid >= graph.vertices().size())
{
System.out.println("** Add.eval(): Invalid edge vertex index in " + aid + " or " + bid + ".");
continue;
}
graph.findOrAddEdge(aid, bid);
}
}
if (faceIndexFns != null)
{
// Add faces by vertex index
for (int f = 0; f < faceIndexFns.length; f++)
{
if (faceIndexFns[f].length < 3)
{
System.out.println("** Add.eval(): Face index list must have at least three entries.");
continue;
}
final int[] vertIds = new int[faceIndexFns[f].length];
int n;
for (n = 0; n < faceIndexFns[f].length; n++)
{
vertIds[n] = faceIndexFns[f][n].eval();
if (vertIds[n] >= graph.vertices().size())
{
System.out.println("** Add.eval(): Invalid face vertex index " + vertIds[n] + ".");
break;
}
}
if (n < faceIndexFns[f].length)
continue; // couldn't load this face
graph.findOrAddFace(vertIds);
}
}
// Now connect new vertices to nearby neighbours, if desired
if (connect)
{
final double threshold = 1.1 * graph.averageEdgeLength();
for (final GraphElement vertexA : newVertices)
for (final GraphElement vertexB : graph.elements(SiteType.Vertex))
{
if (vertexA.id() == vertexB.id())
continue;
if (MathRoutines.distance(vertexA.pt2D(), vertexB.pt2D()) < threshold)
graph.findOrAddEdge(vertexA.id(), vertexB.id());
}
//graph.createFaces();
}
graph.resetBasis();
graph.resetShape();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
boolean isStatic = true;
for (int v = 0; v < vertexFns.length; v++)
for (int n = 0; n < vertexFns[v].length; n++)
isStatic = isStatic && vertexFns[v][n].isStatic();
for (int e = 0; e < edgeFns.length; e++)
for (int v = 0; v < edgeFns[e].length; v++)
for (int n = 0; n < edgeFns[e][v].length; n++)
isStatic = isStatic && edgeFns[e][v][n].isStatic();
for (int f = 0; f < faceFns.length; f++)
for (int v = 0; v < faceFns[f].length; v++)
for (int n = 0; n < faceFns[f][v].length; n++)
isStatic = isStatic && faceFns[f][v][n].isStatic();
return isStatic;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
for (int v = 0; v < vertexFns.length; v++)
for (int n = 0; n < vertexFns[v].length; n++)
flags |= vertexFns[v][n].gameFlags(game);
for (int e = 0; e < edgeFns.length; e++)
for (int v = 0; v < edgeFns[e].length; v++)
for (int n = 0; n < edgeFns[e][v].length; n++)
flags |= edgeFns[e][v][n].gameFlags(game);
for (int f = 0; f < faceFns.length; f++)
for (int v = 0; v < faceFns[f].length; v++)
for (int n = 0; n < faceFns[f][v].length; n++)
flags |= faceFns[f][v][n].gameFlags(game);
if (game.board().defaultSite() != SiteType.Cell)
flags |= GameType.Graph;
return flags;
}
@Override
public void preprocess(final Game game)
{
for (int v = 0; v < vertexFns.length; v++)
for (int n = 0; n < vertexFns[v].length; n++)
vertexFns[v][n].preprocess(game);
for (int e = 0; e < edgeFns.length; e++)
for (int v = 0; v < edgeFns[e].length; v++)
for (int n = 0; n < edgeFns[e][v].length; n++)
edgeFns[e][v][n].preprocess(game);
for (int f = 0; f < faceFns.length; f++)
for (int v = 0; v < faceFns[f].length; v++)
for (int n = 0; n < faceFns[f][v].length; n++)
faceFns[f][v][n].preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
@Override
public String toEnglish(final Game game)
{
return "with additional elements added";
}
}
| 14,848 | 27.123106 | 104 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Clip.java | package game.functions.graph.operators;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.Poly;
import game.util.graph.Vertex;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Returns the result of clipping a graph to a specified shape.
*
* @author cambolbro
*/
public final class Clip extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
private final Polygon polygon;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graphFn Graph to clip.
* @param poly Float points defining clip region.
*
* @example (clip (square 4) (poly { { 1 1 } { 1 3 } { 4 0 } }))
*/
public Clip
(
final GraphFunction graphFn,
final Poly poly
)
{
this.graphFn = graphFn;
polygon = poly.polygon();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph source = graphFn.eval(context, siteType);
if (polygon.size() < 3)
{
System.out.println("** Clip region only has " + polygon.size() + " points.");
return source;
}
polygon.inflate(0.1);
// Create reference lists of vertices and edges based on graphs[0]
final List<Vertex> vertices = new ArrayList<Vertex>();
final List<Edge> edges = new ArrayList<Edge>();
final BitSet remove = new BitSet();
for (final Vertex vertex : source.vertices())
{
final Vertex newVertex = new Vertex(vertices.size(), vertex.pt());
newVertex.setTilingAndShape(vertex.basis(), vertex.shape());
vertices.add(newVertex);
if (polygon.contains(vertex.pt2D()))
remove.set(vertex.id(), true);
}
for (final Edge edge : source.edges())
{
final Vertex va = vertices.get(edge.vertexA().id());
final Vertex vb = vertices.get(edge.vertexB().id());
if (!remove.get(va.id()) && !remove.get(vb.id()))
{
// Add this non-clipped edge
final Edge newEdge = new Edge(edges.size(), va, vb); //, edge.curved());
newEdge.setTilingAndShape(edge.basis(), edge.shape());
edges.add(newEdge);
}
}
// Remove clipped vertices
for (int v = vertices.size() - 1; v >= 0; v--)
if (remove.get(v))
vertices.remove(v); // remove this clipped vertex
// Recalibrate indices
for (int v = 0; v < vertices.size(); v++)
vertices.get(v).setId(v);
final Graph graph = new Graph(vertices, edges);
// System.out.println("Clip has " + result.vertices().size() + " vertices and " +
// result.edges().size() + " edges.");
graph.resetShape();
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
flags |= graphFn.gameFlags(game);
if (game.board().defaultSite() != SiteType.Cell)
flags |= GameType.Graph;
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
@Override
public String toEnglish(final Game game)
{
return "clip the graph to a specified shape";
}
}
| 4,321 | 23.982659 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Complete.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.types.state.GameType;
import game.util.graph.Face;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Creates an edge between each pair of vertices in the graph.
*
* @author cambolbro
*/
public final class Complete extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
private final boolean eachCell;
//-------------------------------------------------------------------------
/**
* @param graph The graph to complete.
* @param eachCell Whether to complete each cell individually.
*
* @example (complete (hex 1))
* @example (complete (hex 3) eachCell:True)
*/
public Complete
(
final GraphFunction graph,
@Opt @Name final Boolean eachCell
)
{
graphFn = graph;
this.eachCell = (eachCell == null) ? false : eachCell.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (eachCell)
{
// Create an edge between all vertex pairs within each cell
for (final Face face : graph.faces())
for (int va = 0; va < face.vertices().size(); va++)
{
final Vertex vertexA = face.vertices().get(va);
for (int vb = va + 1; vb < face.vertices().size(); vb++)
{
final Vertex vertexB = face.vertices().get(vb);
graph.findOrAddEdge(vertexA, vertexB);
}
}
}
else
{
// Create an edge between all vertex pairs within graph
graph.clear(SiteType.Edge);
for (int va = 0; va < graph.vertices().size(); va++)
for (int vb = va + 1; vb < graph.vertices().size(); vb++)
graph.findOrAddEdge(va, vb);
graph.makeFaces(true);
}
graph.resetBasis();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long flags = graphFn.gameFlags(game);
if (game.board().defaultSite() != SiteType.Cell)
flags |= GameType.Graph;
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
@Override
public String toEnglish(final Game game)
{
return "adds an edge between each vertex pair in " + graphFn.toEnglish(game);
}
}
| 3,582 | 23.209459 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Dual.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.BasisType;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Face;
import game.util.graph.Graph;
import other.BaseLudeme;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Returns the weak dual of the specified graph.
*
* @author cambolbro
*
* @remarks The weak dual of a graph is obtained by creating a vertex at the
* midpoint of each face, then connecting with an edge vertices
* corresponding to adjacent faces. This is equivalent to the dual of
* the graph without the single ``outside'' vertex. The weak dual is
* non-transitive and always produces a smaller graph; applying
* (dual (dual <graph>)) does not restore the original graph.
*/
public final class Dual extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graph The graph to take the weak dual of.
*
* @example (dual (square 5))
*/
public Dual
(
final GraphFunction graph
)
{
graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph source = graphFn.eval(context, siteType);
if (source.vertices().isEmpty() || source.edges().isEmpty() || source.faces().isEmpty())
{
System.out.println("** Dual.eval(): Taking dual of graph with no vertices, edges or faces.");
return source;
}
final Graph graph = new Graph();
// Create vertices
for (final Face face : source.faces())
graph.addVertex(face.pt());
if (graph.vertices().isEmpty())
return graph;
// Create edges
for (final Edge edge : source.edges())
if (edge.left() != null && edge.right() != null)
graph.addEdge(edge.left().id(), edge.right().id());
//if (siteType == SiteType.Cell)
graph.makeFaces(false); //true);
graph.setBasisAndShape(BasisType.Dual, ShapeType.NoShape);
graph.reorder();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
@Override
public String toEnglish(final Game game)
{
return ((BaseLudeme) graphFn).toEnglish(game);
}
}
| 3,643 | 24.843972 | 96 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Hole.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import game.util.graph.Poly;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Cuts a hole in a graph according to a specified shape.
*
* @author cambolbro
*
* @remarks Any face of the graph whose midpoint falls within the hole is removed,
* as are any edges or vertices isolated as a result.
*/
public final class Hole extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
private final Polygon polygon;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graphFn Graph to clip.
* @param poly Float points defining hole region.
*
* @example (hole (square 8) (poly { { 2.5 2.5 } { 2.5 5.5 } { 4.5 5.5 } { 4.5 4.5 } {5.5 4.5 } { 5.5 2.5 } }))
*/
public Hole
(
final GraphFunction graphFn,
final Poly poly
)
{
this.graphFn = graphFn;
this.polygon = poly.polygon();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (polygon.size() < 3)
{
System.out.println("** Hole: Clip region only has " + polygon.size() + " points.");
return graph;
}
polygon.inflate(0.1);
for (int fid = graph.faces().size() - 1; fid >= 0; fid--)
if (polygon.contains(graph.faces().get(fid).pt2D()))
graph.removeFace(fid, true);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
flags |= graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 2,921 | 23.35 | 112 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Intersect.java | package game.functions.graph.operators;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Returns the intersection of two or more graphs.
*
* @author cambolbro
*
* @remarks The intersection of two or more graphs is composed of the vertices
* and edges that occur in all of those graphs.
*/
public final class Intersect extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction[] graphFns;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* For making the intersection of two graphs.
*
* @param graphA First graph to intersect.
* @param graphB Second graph to intersect.
*
* @example (intersect (square 4) (rectangle 2 5))
*/
public Intersect
(
final GraphFunction graphA,
final GraphFunction graphB
)
{
this.graphFns = new GraphFunction[2];
this.graphFns[0] = graphA;
this.graphFns[1] = graphB;
}
/**
* For making the intersection of many graphs.
*
* @param graphs Graphs to intersect.
*
* @example (intersect { (rectangle 6 2) (square 4) (rectangle 7 2) })
*/
public Intersect
(
final GraphFunction[] graphs
)
{
this.graphFns = graphs;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final int numGraphs = graphFns.length;
final Graph[] graphs = new Graph[numGraphs];
for (int n = 0; n < numGraphs; n++)
{
final GraphFunction fn = graphFns[n];
graphs[n] = fn.eval(context, siteType);
// System.out.println(graphs[n]);
}
// Note: Retain the tiling and shape of the original elements.
if (numGraphs == 1)
return graphs[0]; // nothing to intersect with
// Create reference lists of vertices and edges based on graphs[0]
final List<Vertex> vertices = new ArrayList<Vertex>();
final List<Edge> edges = new ArrayList<Edge>();
for (final Vertex vertex : graphs[0].vertices())
{
final Vertex newVertex = new Vertex(vertices.size(), vertex.pt());
newVertex.setTilingAndShape(vertex.basis(), vertex.shape());
vertices.add(newVertex);
}
for (final Edge edge : graphs[0].edges())
{
final Vertex va = vertices.get(edge.vertexA().id());
final Vertex vb = vertices.get(edge.vertexB().id());
final Edge newEdge = new Edge(edges.size(), va, vb); //, edge.curved());
newEdge.setTilingAndShape(edge.basis(), edge.shape());
edges.add(newEdge);
}
// Remove edges that do not occur in all subsequent graphs
for (int e = edges.size() - 1; e >= 0; e--)
{
final Edge edge = edges.get(e);
boolean foundInAll = true;
for (int g = 1; g < numGraphs; g++)
{
boolean found = false;
for (final Edge edgeG : graphs[g].edges())
if (edge.coincidentVertices(edgeG, 0.01)) //tolerance))
{
found = true;
break;
}
if (!found)
{
foundInAll = false;
break;
}
}
if (!foundInAll)
edges.remove(e); // no match in this graph, remove it
}
// Remove vertices that do not occur in all subsequent graphs
for (int v = vertices.size() - 1; v >= 0; v--)
{
final Vertex vertex = vertices.get(v);
boolean foundInAll = true;
for (int g = 1; g < numGraphs; g++)
{
boolean found = false;
for (final Vertex vertexG : graphs[g].vertices())
if (vertex.coincident(vertexG, 0.01)) //tolerance))
{
found = true;
break;
}
if (!found)
{
foundInAll = false;
break;
}
}
if (!foundInAll)
vertices.remove(v); // no match in this graph, remove it
}
// Recalibrate indices
for (int v = 0; v < vertices.size(); v++)
vertices.get(v).setId(v);
for (int e = 0; e < edges.size(); e++)
edges.get(e).setId(e);
final Graph graph = new Graph(vertices, edges);
graph.resetBasis();
graph.resetShape();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
for (final GraphFunction fn : graphFns)
if (!fn.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
for (final GraphFunction fn : graphFns)
flags |= fn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
for (final GraphFunction fn : graphFns)
fn.preprocess(game);
if (isStatic())
precomputedGraph = eval
(
new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell)
);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// for (final GraphFunction fn : graphFns)
// concepts.or(fn.concepts(game));
return concepts;
}
}
| 5,673 | 22.840336 | 85 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Keep.java | package game.functions.graph.operators;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.ShapeType;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.Poly;
import game.util.graph.Vertex;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Keeps a specified shape within a graph and discards the remainder.
*
* @author cambolbro
*/
public final class Keep extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
private final Polygon polygon;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graphFn Graph to modify.
* @param poly Float points defining keep region.
*
* @example (keep (square 4) (poly { { 1 1 } { 1 3 } { 4 0 } }))
*/
public Keep
(
final GraphFunction graphFn,
final Poly poly
)
{
this.graphFn = graphFn;
this.polygon = poly.polygon();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph source = graphFn.eval(context, siteType);
if (polygon.size() < 3)
{
System.out.println("** Keep region only has " + polygon.size() + " points.");
return source;
}
polygon.inflate(0.1);
// Create reference lists of vertices and edges based on graphs[0]
final List<Vertex> vertices = new ArrayList<Vertex>();
final List<Edge> edges = new ArrayList<Edge>();
final BitSet remove = new BitSet();
for (final Vertex vertex : source.vertices())
{
final Vertex newVertex = new Vertex(vertices.size(), vertex.pt());
newVertex.setTilingAndShape(vertex.basis(), vertex.shape());
vertices.add(newVertex);
if (!polygon.contains(vertex.pt2D()))
remove.set(vertex.id(), true);
}
for (final Edge edge : source.edges())
{
final Vertex va = vertices.get(edge.vertexA().id());
final Vertex vb = vertices.get(edge.vertexB().id());
if (!remove.get(va.id()) && !remove.get(vb.id()))
{
// Add this non-clipped edge
final Edge newEdge = new Edge(edges.size(), va, vb); //, edge.curved());
newEdge.setTilingAndShape(edge.basis(), edge.shape());
edges.add(newEdge);
}
}
// Remove clipped vertices
for (int v = vertices.size() - 1; v >= 0; v--)
if (remove.get(v))
vertices.remove(v); // remove this clipped vertex
// Recalibrate indices
for (int v = 0; v < vertices.size(); v++)
vertices.get(v).setId(v);
final Graph graph = new Graph(vertices, edges);
graph.setBasisAndShape(source.basis(), ShapeType.NoShape);
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
flags |= graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 4,085 | 24.067485 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Layers.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Face;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.Vector;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Makes multiple layers of the specified graph for 3D games.
*
* @author cambolbro
*
* @remarks The layers are stacked upon each one 1 unit apart. Layers will be
* shown in isometric view from the side in a future version.
*/
public final class Layers extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final int numLayers;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param layers Number of layers.
* @param graph The graph to layer.
*
* @example (layers 3 (square 3)))
*/
public Layers
(
final DimFunction layers,
final GraphFunction graph
)
{
this.numLayers = layers.eval();
this.graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
// Create N copies of graph and merge them into first entry
final Graph[] graphs = new Graph[numLayers];
for (int layer = 0; layer < numLayers; layer++)
{
graphs[layer] = graphFn.eval(context, siteType);
//graphs[layer].scale(1, 0.5, 1); // flatten this layer
//graphs[layer].skew(0.5); // skew for isometric effect
graphs[layer].translate(0, 0, layer); // move this layer N units in z direction
if (layer == 0)
continue;
// Merge with graph 0
final int numVerts = graphs[layer].vertices().size();
final int vertsStartAt = graphs[0].vertices().size();
//final int edgesStartAt = graphs[0].edges().size();
//final int facesStartAt = graphs[0].faces().size();
// Create duplicate vertices in base graph
for (final Vertex vertex : graphs[layer].vertices())
graphs[0].addVertex(vertex.pt());
// Link up any pivots in new vertices
for (final Vertex vertex : graphs[layer].vertices())
if (vertex.pivot() != null)
{
// Link up pivot in new graph
final Vertex newVertex = graphs[0].vertices().get(vertsStartAt + vertex.id());
final int newPivotId = vertsStartAt + vertex.pivot().id();
newVertex.setPivot(graphs[0].vertices().get(newPivotId));
}
// Create duplicate edges in base graph
for (final Edge edge : graphs[layer].edges())
{
final int vidA = vertsStartAt + edge.vertexA().id();
final int vidB = vertsStartAt + edge.vertexB().id();
final Edge newEdge = graphs[0].addEdge(vidA, vidB);
if (edge.tangentA() != null)
newEdge.setTangentA(new Vector(edge.tangentA()));
if (edge.tangentB() != null)
newEdge.setTangentB(new Vector(edge.tangentB()));
}
// Create new vertices between layers
for (int v = 0; v < numVerts; v++)
{
final Vertex vertexA = graphs[0].vertices().get(vertsStartAt - numVerts + v);
final Vertex vertexB = graphs[0].vertices().get(vertsStartAt + v);
graphs[0].addEdge(vertexA, vertexB);
}
// Create new faces
for (final Face face : graphs[layer].faces())
{
final int[] vids = new int[face.vertices().size()];
for (int n = 0; n < face.vertices().size(); n++)
vids[n] = vertsStartAt + face.vertices().get(n).id();
graphs[0].findOrAddFace(vids);
}
}
graphs[0].reorder();
//System.out.println(graph);
return graphs[0];
}
//-------------------------------------------------------------------------
// /**
// * Merge vertex vv into vertex v.
// */
// void mergeVertices(final List<Vertex> vertices, final List<Edge> edges)
// {
// for (int v = 0; v < vertices.size(); v++)
// {
// final Vertex base = vertices.get(v);
//
// for (int vv = vertices.size()-1; vv > v; vv--)
// {
// final Vertex other = vertices.get(vv);
// if (base.coincident(other, tolerance))
// mergeVertices(vertices, edges, v, vv);
// }
// }
// }
//
// /**
// * Merge vertex vv into vertex v.
// */
// @SuppressWarnings("static-method")
// void mergeVertices
// (
// final List<Vertex> vertices, final List<Edge> edges,
// final int vid, final int coincidentId
// )
// {
// final Vertex survivor = vertices.get(vid);
//
// // Redirect all references to coincident vertex as pivot
// for (final Vertex vertex : vertices)
// if (vertex.pivot() != null && vertex.pivot().id() == coincidentId)
// vertex.setPivot(survivor); // redirect to surviving vertex
//
// // Redirect edge references to coincident to vertex
// for (final Edge edge : edges)
// {
// if (edge.vertexA().id() == coincidentId)
// edge.setVertexA(survivor);
// if (edge.vertexB().id() == coincidentId)
// edge.setVertexB(survivor);
// }
//
// // Renumber vertices above coincidentId and remove coincident vertex
// for (int n = coincidentId + 1; n < vertices.size(); n++)
// {
// final Vertex vertexN = vertices.get(n);
// vertexN.setId(vertexN.id() - 1);
// }
//
// vertices.remove(coincidentId);
// }
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
flags |= graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 6,414 | 26.41453 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/MakeFaces.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Recreates all possible non-overlapping faces for the given graph.
*
* @author cambolbro
*/
public final class MakeFaces extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graph The graph to be modified.
*
* @example (makeFaces (square 5))
*/
public MakeFaces
(
final GraphFunction graph
)
{
this.graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
graph.makeFaces(true);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 2,216 | 21.85567 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Merge.java | package game.functions.graph.operators;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import main.math.Vector;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Returns the result of merging two or more graphs.
*
* @author cambolbro
*
* @remarks The graphs are overlaid with each other, such that incident vertices
* (i.e. those with the same location) are merged into a single vertex.
*/
public final class Merge extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* A pivot pair.
*/
public class PivotPair
{
/**
* The index.
*/
public int id;
/**
* The index of the pivot.
*/
public int pivotId;
/**
* @param id the index.
* @param pivotId The index of the pivot.
*/
public PivotPair(final int id, final int pivotId)
{
this.id = id;
this.pivotId = pivotId;
}
}
//-------------------------------------------------------------------------
private final GraphFunction[] graphFns;
private final boolean connect;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* For making the merge of two graphs.
*
* @param graphA First graph to merge.
* @param graphB Second graph to merge.
* @param connect Whether to connect newly added vertices to nearby neighbours
* [False].
*
* @example (merge (rectangle 6 2) (rectangle 3 5))
*/
public Merge
(
final GraphFunction graphA,
final GraphFunction graphB,
@Opt @Name final Boolean connect
)
{
this.graphFns = new GraphFunction[2];
this.graphFns[0] = graphA;
this.graphFns[1] = graphB;
this.connect = (connect == null) ? false : connect.booleanValue();
}
/**
* For making the merge of many graphs.
*
* @param graphs Graphs to merge.
* @param connect Whether to connect newly added vertices to nearby neighbours
* [False].
*
* @example (merge { (rectangle 6 2) (square 4) (rectangle 7 2) })
*/
public Merge
(
final GraphFunction[] graphs,
@Opt @Name final Boolean connect
)
{
this.graphFns = graphs;
this.connect = (connect == null) ? false : connect.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph[] graphs = new Graph[graphFns.length];
for (int n = 0; n < graphFns.length; n++)
{
final GraphFunction fn = graphFns[n];
graphs[n] = fn.eval(context, siteType);
}
// Note: Retain the tiling and shape of the original elements.
// Collate vertices and edges
final List<Vertex> vertices = new ArrayList<Vertex>();
final List<Edge> edges = new ArrayList<Edge>();
int offset = 0;
for (final Graph subGraph : graphs)
{
for (final Vertex vertex : subGraph.vertices())
{
final Vertex newVertex = new Vertex(vertices.size(), vertex.pt().x(), vertex.pt().y(), vertex.pt().z());
newVertex.setTilingAndShape(vertex.basis(), vertex.shape());
if (vertex.pivot() != null)
{
// **
// ** FIXME: Will be reference to old pivot, not new one.
// **
newVertex.setPivot(vertex.pivot());
}
vertices.add(newVertex);
}
for (final Edge edge : subGraph.edges())
{
final Vertex va = vertices.get(edge.vertexA().id() + offset);
final Vertex vb = vertices.get(edge.vertexB().id() + offset);
final Edge newEdge = new Edge(edges.size(), va, vb); //, edge.curved());
newEdge.setTilingAndShape(edge.basis(), edge.shape());
if (edge.tangentA() != null)
newEdge.setTangentA(new Vector(edge.tangentA()));
if (edge.tangentB() != null)
newEdge.setTangentB(new Vector(edge.tangentB()));
edges.add(newEdge);
}
offset += subGraph.vertices().size();
}
// Merge incident vertices
mergeVertices(vertices, edges);
game.util.graph.Graph.removeDuplicateEdges(edges);
final Graph graph = new Graph(vertices, edges);
// Now connect new vertices to nearby neighbours, if desired
if (connect)
{
final double threshold = 1.1 * graph.averageEdgeLength();
for (final Vertex vertexA : graph.vertices())
for (final Vertex vertexB : graph.vertices())
{
if (vertexA.id() == vertexB.id())
continue;
if (MathRoutines.distance(vertexA.pt2D(), vertexB.pt2D()) < threshold)
graph.findOrAddEdge(vertexA.id(), vertexB.id());
}
graph.makeFaces(true);
}
graph.resetBasis();
graph.resetShape();
//System.out.println(graph);
// System.out.println("Merge has " + graph.vertices().size() + " vertices and " +
// graph.edges().size() + " edges.");
return graph;
}
//-------------------------------------------------------------------------
/**
* Merge vertex vv into vertex v.
*/
private static void mergeVertices(final List<Vertex> vertices, final List<Edge> edges)
{
for (int v = 0; v < vertices.size(); v++)
{
final Vertex base = vertices.get(v);
for (int vv = vertices.size()-1; vv > v; vv--)
{
final Vertex other = vertices.get(vv);
if (base.coincident(other, 0.01)) // use more tolerance than usual
mergeVertices(vertices, edges, v, vv);
}
}
}
/**
* Merge vertex vv into vertex v.
*/
private static void mergeVertices
(
final List<Vertex> vertices, final List<Edge> edges,
final int vid, final int coincidentId
)
{
final Vertex survivor = vertices.get(vid);
// Redirect all references to coincident vertex as pivot
for (final Vertex vertex : vertices)
if (vertex.pivot() != null && vertex.pivot().id() == coincidentId)
vertex.setPivot(survivor); // redirect to surviving vertex
// Redirect edge references to coincident to vertex
for (final Edge edge : edges)
{
if (edge.vertexA().id() == coincidentId)
edge.setVertexA(survivor);
if (edge.vertexB().id() == coincidentId)
edge.setVertexB(survivor);
}
// Renumber vertices above coincidentId and remove coincident vertex
for (int n = coincidentId + 1; n < vertices.size(); n++)
{
final Vertex vertexN = vertices.get(n);
vertexN.setId(vertexN.id() - 1);
}
vertices.remove(coincidentId);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
for (final GraphFunction fn : graphFns)
if (!fn.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
for (final GraphFunction fn : graphFns)
flags |= fn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
for (final GraphFunction fn : graphFns)
fn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling or shape.
// for (final GraphFunction fn : graphFns)
// concepts.or(fn.concepts(game));
return concepts;
}
}
| 7,941 | 24.954248 | 108 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Recoordinate.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Regenerates the coordinate labels for the elements of a graph.
*
* @author cambolbro
*/
public final class Recoordinate extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final SiteType siteTypeA;
private final SiteType siteTypeB;
private final SiteType siteTypeC;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param siteTypeA First site type to recoordinate (Vertex/Edge/Cell).
* @param siteTypeB Second site type to recoordinate (Vertex/Edge/Cell).
* @param siteTypeC Third site type to recoordinate (Vertex/Edge/Cell).
* @param graph The graph whose vertices are to be renumbered.
*
* @example (recoordinate (merge (rectangle 2 5) (square 5)))
* @example (recoordinate Vertex (merge (rectangle 2 5) (square 5)))
*/
public Recoordinate
(
@Opt final SiteType siteTypeA,
@Opt final SiteType siteTypeB,
@Opt final SiteType siteTypeC,
final GraphFunction graph
)
{
this.graphFn = graph;
this.siteTypeA = siteTypeA;
this.siteTypeB = siteTypeB;
this.siteTypeC = siteTypeC;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
final BitSet types = new BitSet();
if (siteTypeA != null)
types.set(siteTypeA.ordinal());
if (siteTypeB != null)
types.set(siteTypeB.ordinal());
if (siteTypeC != null)
types.set(siteTypeC.ordinal());
// if (types.cardinality() == 0)
// {
// // No site type specified, renumber everything
// graph.setCoordinates();
// }
// else
// {
// // Only renumber those site types specified
// if (types.get(0))
// graph.setCoordinates(SiteType.Vertex);
//
// if (types.get(1))
// graph.setCoordinates(SiteType.Edge);
//
// if (types.get(2))
// {
// graph.setCoordinates(SiteType.Cell);
//
// // Already called in Graph.orderFaces()
// //result.setFacePhases(); // as face 0 might have changed
// }
// }
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 3,531 | 24.049645 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Remove.java | package game.functions.graph.operators;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import annotations.Name;
import annotations.Opt;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Face;
import game.util.graph.Graph;
import game.util.graph.Poly;
import game.util.graph.Vertex;
import main.math.Polygon;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Removes elements from a graph.
*
* @author cambolbro
*
* @remarks The elements to be removed can be vertices, edges or faces.
* Elements whose vertices can't be found will be ignored.
* Be careful when removing by index, as the graph is modified and
* renumbered with each removal. It is recommended to specify indices
* in decreasing order and to avoid removing vertices, edges and/or
* faces by index on the same call (instead, you can chain multiple
* removals by index together, one for each element type).
*/
public final class Remove extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
private final Polygon polygon;
private final Float[][][] facePositions;
private final Float[][][] edgePositions;
private final Float[][] vertexPositions;
private final DimFunction[] faceIndices;
private final DimFunction[][] edgeIndices;
private final DimFunction[] vertexIndices;
private final boolean trimEdges;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* For removing some graph elements.
*
* @param graph The graph to remove elements from.
* @param cells Locations of vertices of faces to remove.
* @param Cells Indices of faces to remove.
* @param edges Locations of end points of edges to remove.
* @param Edges Indices of end points of edges to remove.
* @param vertices Locations of vertices to remove.
* @param Vertices Indices of vertices to remove.
* @param trimEdges Whether to trim edges orphaned by removing faces [True].
*
* @example (remove (square 4) vertices:{ { 0.0 3.0 } { 0.5 2 } })
* @example (remove (square 4) cells:{ 0 1 2 } edges:{ {0 1} {1 2} } vertices:{
* 1 4 })
*/
public Remove
(
final GraphFunction graph,
@Opt @Or @Name final Float[][][] cells,
@Opt @Or @Name final DimFunction[] Cells,
@Opt @Or2 @Name final Float[][][] edges,
@Opt @Or2 @Name final DimFunction[][] Edges,
@Opt @Or @Name final Float[][] vertices,
@Opt @Or @Name final DimFunction[] Vertices,
@Opt @Name final Boolean trimEdges
)
{
int numNonNullF = 0;
if (cells != null)
numNonNullF++;
if (Cells != null)
numNonNullF++;
if (numNonNullF > 1)
throw new IllegalArgumentException("Only one 'cell' parameter can be non-null.");
int numNonNullE = 0;
if (edges != null)
numNonNullE++;
if (Edges != null)
numNonNullE++;
if (numNonNullE > 1)
throw new IllegalArgumentException("Only one 'edge' parameter can be non-null.");
int numNonNullV = 0;
if (vertices != null)
numNonNullV++;
if (Vertices != null)
numNonNullV++;
if (numNonNullV > 1)
throw new IllegalArgumentException("Only one 'vertex' parameter can be non-null.");
this.graphFn = graph;
this.polygon = null;
this.facePositions = cells;
this.edgePositions = edges;
this.vertexPositions = vertices;
this.faceIndices = Cells;
this.edgeIndices = Edges;
this.vertexIndices = Vertices;
this.trimEdges = (trimEdges == null) ? true : trimEdges.booleanValue();
}
/**
* For removing some elements according to a polygon.
*
* @param graphFn Graph to clip.
* @param poly Float points defining hole region.
* @param trimEdges Whether to trim edges orphaned by removing faces [True].
*
* @example (remove (square 8) (poly { { 2.5 2.5 } { 2.5 5.5 } { 4.5 5.5 } { 4.5
* 4.5 } {5.5 4.5 } { 5.5 2.5 } }))
*/
public Remove
(
final GraphFunction graphFn,
final Poly poly,
@Opt @Name final Boolean trimEdges
)
{
this.graphFn = graphFn;
this.polygon = poly.polygon();
this.facePositions = null;
this.edgePositions = null;
this.vertexPositions = null;
this.faceIndices = null;
this.edgeIndices = null;
this.vertexIndices = null;
this.trimEdges = (trimEdges == null) ? true : trimEdges.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
// Note: Retain the tiling and shape of the original elements.
if (polygon != null)
{
for (int vid = graph.vertices().size() - 1; vid >= 0; vid--)
{
final Vertex vertex = graph.vertices().get(vid);
if (polygon.contains(vertex.pt2D()))
graph.removeVertex(vertex);
}
// // Check intersecting edges?
// for (int eid = graph.edges().size() - 1; eid >= 0; eid--)
// {
// final Edge edge = graph.edges().get(eid);
// if (polygon.contains(edge.vertexA().pt2D()) ||polygon.contains(edge.vertexB().pt2D()))
// graph.remove(edge);
// }
// Check intersecting faces?
// ...
}
// Remove faces
if (facePositions != null)
{
for (final Float[][] pts : facePositions)
{
final int[] vertIds = new int[pts.length];
for (int n = 0; n < pts.length; n++)
{
if (pts[n].length < 2)
{
System.out.println("** Remove: Two values expected for vertex.");
continue;
}
// Find vertex
final double x = pts[n][0].floatValue();
final double y = pts[n][1].floatValue();
final double z = (pts[n].length > 2) ? pts[n][2].floatValue() : 0;
final Vertex vertex = graph.findVertex(x, y, z);
if (vertex == null)
{
System.out.println("** Couldn't find face vertex.");
vertIds[n] = -1; // make sure an obvious error occurs
}
else
{
vertIds[n] = vertex.id();
}
}
final Face face = graph.findFace(vertIds);
if (face != null)
graph.remove(face, trimEdges);
else
System.out.println("** Face not found from vertices.");
}
}
else if (faceIndices != null)
{
final List<Integer> list = new ArrayList<Integer>();
for (final DimFunction id : faceIndices)
list.add(Integer.valueOf(id.eval()));
Collections.sort(list);
Collections.reverse(list);
for (final Integer id : list)
graph.removeFace(id.intValue(), trimEdges);
}
// Remove edges
if (edgePositions != null)
{
for (final Float[][] pts : edgePositions)
{
final double ax = pts[0][0].floatValue();
final double ay = pts[0][1].floatValue();
final double az = (pts[0].length > 2) ? pts[0][2].floatValue() : 0;
final double bx = pts[1][0].floatValue();
final double by = pts[1][1].floatValue();
final double bz = (pts[1].length > 2) ? pts[1][2].floatValue() : 0;
final Vertex vertexA = graph.findVertex(ax, ay, az);
final Vertex vertexB = graph.findVertex(bx, by, bz);
if (vertexA != null && vertexB != null)
{
final Edge edge = graph.findEdge(vertexA, vertexB);
if (edge != null)
graph.remove(edge, false);
else
System.out.println("** Edge vertices not found.");
}
else
{
System.out.println("** Edge vertices not found.");
}
}
}
else if (this.edgeIndices != null)
{
for (final DimFunction[] vids : edgeIndices)
{
if (vids.length == 2)
graph.removeEdge(vids[0].eval(), vids[1].eval());
}
}
// Remove vertices
if (vertexPositions != null)
{
for (final Float[] pt : vertexPositions)
{
final double x = pt[0].floatValue();
final double y = pt[1].floatValue();
final double z = (pt.length > 2) ? pt[2].floatValue() : 0;
final Vertex vertex = graph.findVertex(x, y, z);
if (vertex != null)
graph.removeVertex(vertex);
}
}
else if (vertexIndices != null)
{
final List<Integer> list = new ArrayList<Integer>();
for (final DimFunction id : vertexIndices)
list.add(Integer.valueOf(id.eval()));
Collections.sort(list);
Collections.reverse(list);
for (final Integer id : list)
graph.removeVertex(id.intValue());
}
// **
// ** Do not create faces! That would just restore any deleted faces.
// **
//if (siteType == SiteType.Cell)
// graph.createFaces();
// **
// ** Don't reorder, in case ordering matters for other parts of the board.
// ** The Graph decrements indices to cater for gaps left by removed elements.
// **
//graph.reorder();
graph.resetShape();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
final boolean isStatic = true;
return isStatic;
}
@Override
public long gameFlags(final Game game)
{
final long flags = 0;
return flags;
}
@Override
public void preprocess(final Game game)
{
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 10,164 | 26.697548 | 92 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Renumber.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
/**
* Renumbers the vertices of a graph into sequential order.
*
* @author cambolbro
*
* @remarks Vertices are renumbered from the lower left rightwards and upwards,
* in an upwards reading order. Renumbering can be useful after a
* union or merge operation combines different graphs.
*/
public final class Renumber extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final SiteType siteTypeA;
private final SiteType siteTypeB;
private final SiteType siteTypeC;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param siteTypeA First site type to renumber (Vertex/Edge/Cell).
* @param siteTypeB Second site type to renumber (Vertex/Edge/Cell).
* @param siteTypeC Third site type to renumber (Vertex/Edge/Cell).
* @param graph The graph whose vertices are to be renumbered.
*
* @example (renumber (merge (rectangle 2 5) (square 5)))
* @example (renumber Vertex (merge (rectangle 2 5) (square 5)))
*/
public Renumber
(
@Opt final SiteType siteTypeA,
@Opt final SiteType siteTypeB,
@Opt final SiteType siteTypeC,
final GraphFunction graph
)
{
this.graphFn = graph;
this.siteTypeA = siteTypeA;
this.siteTypeB = siteTypeB;
this.siteTypeC = siteTypeC;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph result = graphFn.eval(context, siteType);
if (result.vertices().isEmpty())
{
System.out.println("** Rotate.eval(): Rotating empty graph.");
return result;
}
final BitSet types = new BitSet();
if (siteTypeA != null)
types.set(siteTypeA.ordinal());
if (siteTypeB != null)
types.set(siteTypeB.ordinal());
if (siteTypeC != null)
types.set(siteTypeC.ordinal());
if (types.cardinality() == 0)
{
// No site type specified, renumber everything
result.reorder();
}
else
{
// Only renumber those site types specified
if (types.get(0))
result.reorder(SiteType.Vertex);
if (types.get(1))
result.reorder(SiteType.Edge);
if (types.get(2))
{
result.reorder(SiteType.Cell);
// Already called in Graph.orderFaces()
//result.setFacePhases(); // as face 0 might have changed
}
}
return result;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 3,704 | 24.033784 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Rotate.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.floats.FloatFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.BaseLudeme;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Rotates a graph by the specified number of degrees anticlockwise.
*
* @author cambolbro
*
* @remarks The vertices within the graph are rotated about the graph's midpoint.
*/
public final class Rotate extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final FloatFunction degreesFn;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param degreesFn Number of degrees to rotate anticlockwise.
* @param graph The graph to rotate.
*
* @example (rotate 45 (square 5))
*/
public Rotate
(
final FloatFunction degreesFn,
final GraphFunction graph
)
{
this.degreesFn = degreesFn;
graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (graph.vertices().isEmpty())
{
System.out.println("** Rotate.eval(): Rotating empty graph.");
return graph;
}
// Rotate the graph
final double degrees = degreesFn.eval(context);
graph.rotate(degrees);
//graph.reorder();
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic() && degreesFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game) | degreesFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
degreesFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
@Override
public String toEnglish(final Game game)
{
return "rotated " + ((BaseLudeme) graphFn).toEnglish(game);
}
}
| 2,849 | 22.360656 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Scale.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.floats.FloatFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Scales a graph by the specified amount.
*
* @author cambolbro
*
* This operation modifies the locations of vertices within the graph.
*/
public final class Scale extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final FloatFunction scaleXFn;
private final FloatFunction scaleYFn;
private final FloatFunction scaleZFn;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param scaleX Amount to scale in the x direction.
* @param scaleY Amount to scale in the y direction [scaleX].
* @param scaleZ Amount to scale in the z direction [1].
* @param graph The graph to scale.
*
* @example (scale 2 (square 5))
* @example (scale 2 3.5 (square 5))
*/
public Scale
(
final FloatFunction scaleX,
@Opt final FloatFunction scaleY,
@Opt final FloatFunction scaleZ,
final GraphFunction graph
)
{
this.graphFn = graph;
this.scaleXFn = scaleX;
this.scaleYFn = scaleY;
this.scaleZFn = scaleZ;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (graph.vertices().isEmpty())
{
System.out.println("** Rotate.eval(): Rotating empty graph.");
return graph;
}
// Scale the graph
final double sx = scaleXFn.eval(context);
final double sy = (scaleYFn != null) ? scaleYFn.eval(context) : scaleXFn.eval(context);
final double sz = (scaleZFn != null) ? scaleZFn.eval(context) : 1;
graph.scale(sx, sy, sz);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic()
&&
scaleXFn.isStatic() && scaleYFn.isStatic() && scaleZFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game)
|
scaleXFn.gameFlags(game) | scaleYFn.gameFlags(game) | scaleZFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
scaleXFn.preprocess(game);
scaleYFn.preprocess(game);
scaleZFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 3,340 | 24.503817 | 89 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Shift.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.floats.FloatFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Translate a graph by the specified x, y and z amounts.
*
* @author cambolbro
*
* @remarks This operation modifies the locations of vertices within the graph.
*/
public final class Shift extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final FloatFunction dxFn;
private final FloatFunction dyFn;
private final FloatFunction dzFn;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param dx Amount to translate in the x direction.
* @param dy Amount to translate in the y direction.
* @param dz Amount to translate in the z direction [0].
* @param graph The graph to rotate.
*
* @example (shift 0 10 (square 5))
*/
public Shift
(
final FloatFunction dx,
final FloatFunction dy,
@Opt final FloatFunction dz,
final GraphFunction graph
)
{
this.graphFn = graph;
this.dxFn = dx;
this.dyFn = dy;
this.dzFn = dz;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (graph.vertices().isEmpty())
{
System.out.println("** Rotate.eval(): Rotating empty graph.");
return graph;
}
// Translate the graph
final double dx = dxFn.eval(context);
final double dy = dyFn.eval(context);
final double dz = (dzFn != null) ? dzFn.eval(context) : 0;
graph.translate(dx, dy, dz);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic()
&&
dxFn.isStatic() && dyFn.isStatic() && dzFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game)
|
dxFn.gameFlags(game) | dyFn.gameFlags(game) | dzFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
dxFn.preprocess(game);
dyFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 3,180 | 23.658915 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Skew.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Skews a graph by the specified amount.
*
* @author cambolbro
*
* Skewing a graph can be useful for achieving a 3D isometric look.
*/
public final class Skew extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final double amount;
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param amount Amount to skew (1 gives a 45 degree skew).
* @param graph The graph to scale.
*
* @example (skew .5 (square 5))
*/
public Skew
(
final Float amount,
final GraphFunction graph
)
{
this.amount = amount.floatValue();
this.graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (graph.vertices().isEmpty())
{
System.out.println("** Rotate.eval(): Rotating empty graph.");
return graph;
}
graph.skew(amount);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 2,419 | 21.407407 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/SplitCrossings.java | package game.functions.graph.operators;
import java.awt.geom.Point2D;
import java.util.BitSet;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import main.math.Point3D;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Splits edge crossings within a graph to create a new vertex at each crossing point.
*
* @author cambolbro
*/
public final class SplitCrossings extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graph The graph to split edge crossings.
*
* @example (splitCrossings (merge (rectangle 2 5) (square 5)))
*/
public SplitCrossings
(
final GraphFunction graph
)
{
this.graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
// System.out.println("\n" + graph);
// boolean didSplit;
// do
// {
// didSplit = false;
// for (int ea = 0; ea < graph.edges().size() && !didSplit; ea++)
// {
// final Edge edgeA = graph.edges().get(ea);
// final Point3D ptAA = edgeA.vertexA().pt();
// final Point3D ptAB = edgeA.vertexB().pt();
//
// Vertex pivot = null;
// if (edgeA.vertexA().pivot() != null)
// pivot = edgeA.vertexA().pivot();
// if (edgeA.vertexB().pivot() != null)
// pivot = edgeA.vertexB().pivot();
//
// for (int eb = ea + 1; eb < graph.edges().size() && !didSplit; eb++)
// {
// final Edge edgeB = graph.edges().get(eb);
// final Point3D ptBA = edgeB.vertexA().pt();
// final Point3D ptBB = edgeB.vertexB().pt();
//
// if (pivot == null && edgeB.vertexA().pivot() != null)
// pivot = edgeB.vertexA().pivot();
// if (pivot == null && edgeB.vertexB().pivot() != null)
// pivot = edgeB.vertexB().pivot();
//
// final Point2D ptX = MathRoutines.crossingPoint
// (
// ptAA.x(), ptAA.y(), ptAB.x(), ptAB.y(),
// ptBA.x(), ptBA.y(), ptBB.x(), ptBB.y()
// );
// if (ptX != null)
// {
// // Edges cross, split them
// final Vertex vertex = graph.addVertex(ptX.getX(), ptX.getY());
// final int vid = vertex.id(); //graph.vertices().size() - 1;
//
// if (pivot != null)
// vertex.setPivot(pivot);
//
//// System.out.println("Splitting edges " + edgeA.id() + " and " + edgeB.id() + "...");
//
// graph.removeEdge(eb); //, false); // remove eb first as has higher index
// graph.removeEdge(ea); //, false);
//
// graph.findOrAddEdge(edgeA.vertexA().id(), vid);
// graph.findOrAddEdge(vid, edgeA.vertexB().id());
//
// graph.findOrAddEdge(edgeB.vertexA().id(), vid);
// graph.findOrAddEdge(vid, edgeB.vertexB().id());
//
//// System.out.println("\n" + graph);
//
// didSplit = true;
// }
// }
// }
// } while (didSplit);
splitAtCrossingPoints(graph);
// Now check for cases where vertices lie on an edge that needs to be split.
// This can happen when multiple edges cross at the same point in the middle,
// e.g. in the Game of Solomon.
splitAtTouchingPoints(graph);
graph.makeFaces(true);
graph.resetBasis();
// System.out.println("\n" + graph);
return graph;
}
//-------------------------------------------------------------------------
static void splitAtCrossingPoints(final Graph graph)
{
boolean didSplit;
do
{
didSplit = false;
for (int ea = 0; ea < graph.edges().size() && !didSplit; ea++)
{
final Edge edgeA = graph.edges().get(ea);
final Point3D ptAA = edgeA.vertexA().pt();
final Point3D ptAB = edgeA.vertexB().pt();
Vertex pivot = null;
if (edgeA.vertexA().pivot() != null)
pivot = edgeA.vertexA().pivot();
if (edgeA.vertexB().pivot() != null)
pivot = edgeA.vertexB().pivot();
for (int eb = ea + 1; eb < graph.edges().size() && !didSplit; eb++)
{
final Edge edgeB = graph.edges().get(eb);
final Point3D ptBA = edgeB.vertexA().pt();
final Point3D ptBB = edgeB.vertexB().pt();
if (pivot == null && edgeB.vertexA().pivot() != null)
pivot = edgeB.vertexA().pivot();
if (pivot == null && edgeB.vertexB().pivot() != null)
pivot = edgeB.vertexB().pivot();
final Point2D ptX = MathRoutines.crossingPoint
(
ptAA.x(), ptAA.y(), ptAB.x(), ptAB.y(),
ptBA.x(), ptBA.y(), ptBB.x(), ptBB.y()
);
if (ptX == null)
continue;
// Edges cross, split them
final Vertex vertex = graph.addVertex(ptX.getX(), ptX.getY());
final int vid = vertex.id(); //graph.vertices().size() - 1;
if (pivot != null)
vertex.setPivot(pivot);
// System.out.println("Splitting edges " + edgeA.id() + " and " + edgeB.id() + "...");
graph.removeEdge(eb); // remove eb first as has higher index
graph.removeEdge(ea);
graph.findOrAddEdge(edgeA.vertexA().id(), vid);
graph.findOrAddEdge(vid, edgeA.vertexB().id());
graph.findOrAddEdge(edgeB.vertexA().id(), vid);
graph.findOrAddEdge(vid, edgeB.vertexB().id());
// System.out.println("\n" + graph);
didSplit = true;
}
}
} while (didSplit);
}
//-------------------------------------------------------------------------
static void splitAtTouchingPoints(final Graph graph)
{
boolean didSplit;
do
{
didSplit = false;
for (int ea = 0; ea < graph.edges().size() && !didSplit; ea++)
{
final Edge edgeA = graph.edges().get(ea);
final Point3D ptAA = edgeA.vertexA().pt();
final Point3D ptAB = edgeA.vertexB().pt();
Vertex pivot = null;
if (edgeA.vertexA().pivot() != null)
pivot = edgeA.vertexA().pivot();
if (edgeA.vertexB().pivot() != null)
pivot = edgeA.vertexB().pivot();
for (final Vertex vertex : graph.vertices())
{
if (edgeA.contains(vertex))
continue;
// Check vertex
final Point3D ptT = MathRoutines.touchingPoint(vertex.pt(), ptAA, ptAB);
if (ptT == null)
continue;
// Edge touched by vertex BA, split it
if (pivot != null)
vertex.setPivot(pivot);
// System.out.println("T: Splitting edge " + edgeA.id() + " at vertex " + vertex.id() + "...\n");
graph.removeEdge(ea);
graph.findOrAddEdge(edgeA.vertexA().id(), vertex.id());
graph.findOrAddEdge(vertex.id(), edgeA.vertexB().id());
didSplit = true;
}
}
} while (didSplit);
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 8,085 | 27.076389 | 101 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Subdivide.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.dim.DimFunction;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Face;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Subdivides graph cells about their midpoint.
*
* @author cambolbro
*
* @remarks Each cell with N sides, where N > min, will be split into N cells.
*/
public final class Subdivide extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
private final int min;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graph The graph to subdivide.
* @param min Minimum cell size to subdivide [1].
*
* @example (subdivide (tiling T3464 2) min:6)
*/
public Subdivide
(
final GraphFunction graph,
@Opt @Name final DimFunction min
)
{
this.graphFn = graph;
this.min = (min == null) ? 1 : min.eval();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
if (siteType == SiteType.Vertex)
graph.makeFaces(true); // can't subdivide without any faces!
for (final Face face : graph.faces())
face.setFlag(false);
for (int fid = graph.faces().size() - 1; fid >= 0; fid--)
{
// Split this face around its midpoint
final Face face = graph.faces().get(fid);
if (face.vertices().size() < min)
continue;
final Vertex pivot = graph.addVertex(face.pt());
for (final Vertex vertex : face.vertices())
graph.findOrAddEdge(pivot.id(), vertex.id());
face.setFlag(true); // flag this existing face for removal
}
if (siteType == SiteType.Cell)
{
// Delete faces *after* subdivision faces have been added,
// otherwise shared edges might also be removed.
for (int fid = graph.faces().size() - 1; fid >= 0; fid--)
if (graph.faces().get(fid).flag())
graph.removeFace(fid, false);
// Create new faces
graph.makeFaces(true);
}
else
{
graph.clear(SiteType.Cell);
}
graph.resetBasis();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 3,628 | 23.355705 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Trim.java | package game.functions.graph.operators;
import java.util.BitSet;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Graph;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Trims orphan vertices and edges from a graph.
*
* @author cambolbro
*
* @remarks An orphan vertex is a vertex with no incident edge
* (note that pivot vertices are not removed).
* An orphan edge is an edge with an end point that has no
* incident edges apart from the edge itself.
*/
public final class Trim extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
private final GraphFunction graphFn;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* @param graph The graph to be trimmed.
*
* @example (trim (dual (square 5)))
*/
public Trim
(
final GraphFunction graph
)
{
this.graphFn = graph;
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph graph = graphFn.eval(context, siteType);
graph.trim();
//System.out.println(graph);
return graph;
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return graphFn.isStatic();
}
@Override
public long gameFlags(final Game game)
{
final long flags = graphFn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
graphFn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling
// concepts.or(graphFn.concepts(game));
return concepts;
}
}
| 2,470 | 22.533333 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/Union.java | package game.functions.graph.operators;
import java.util.BitSet;
import annotations.Name;
import annotations.Opt;
import game.Game;
import game.functions.graph.BaseGraphFunction;
import game.functions.graph.GraphFunction;
import game.types.board.SiteType;
import game.util.graph.Edge;
import game.util.graph.Face;
import game.util.graph.Graph;
import game.util.graph.Vertex;
import main.math.MathRoutines;
import other.context.Context;
//-----------------------------------------------------------------------------
/**
* Returns the union of two or more graphs.
*
* @author cambolbro
*
* @remarks The graphs are simply combined with each other, with no connection between them.
*/
public final class Union extends BaseGraphFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* A pair of pivots.
*/
public class PivotPair
{
/**
* The id of the pair.
*/
public int id;
/**
* The id of the pivot.
*/
public int pivotId;
/**
* Constructor.
*
* @param id The id of the pair.
* @param pivotId The id of the pivot.
*/
public PivotPair(final int id, final int pivotId)
{
this.id = id;
this.pivotId = pivotId;
}
}
//-------------------------------------------------------------------------
private final GraphFunction[] graphFns;
private final boolean connect;
/** Precompute once and cache, if possible. */
private Graph precomputedGraph = null;
//-------------------------------------------------------------------------
/**
* For making the union of two graphs.
*
* @param graphA First graph to combine.
* @param graphB Second graph to combine.
* @param connect Whether to connect newly added vertices to nearby neighbours
* [False].
*
* @example (union (square 5) (square 3))
*/
public Union
(
final GraphFunction graphA,
final GraphFunction graphB,
@Name @Opt final Boolean connect
)
{
this.graphFns = new GraphFunction[2];
this.graphFns[0] = graphA;
this.graphFns[1] = graphB;
this.connect = (connect == null) ? false : connect.booleanValue();
}
/**
* For making the union of many graphs.
*
* @param graphs Graphs to merge.
* @param connect Whether to connect newly added vertices to nearby neighbours
* [False].
*
* @example (union { (rectangle 6 2) (square 4) (rectangle 7 2) })
*/
public Union
(
final GraphFunction[] graphs,
@Name @Opt final Boolean connect
)
{
this.graphFns = graphs;
this.connect = (connect == null) ? false : connect.booleanValue();
}
//-------------------------------------------------------------------------
@Override
public Graph eval(final Context context, final SiteType siteType)
{
if (precomputedGraph != null)
return precomputedGraph;
final Graph[] graphs = new Graph[graphFns.length];
for (int n = 0; n < graphFns.length; n++)
{
final GraphFunction fn = graphFns[n];
graphs[n] = fn.eval(context, siteType);
//System.out.println("Graph " + n + ":\n" + graphs[n]);
}
// Note: Retain the tiling and shape of the original elements.
// // Collate vertices and edges
// final List<Vertex> vertices = new ArrayList<Vertex>();
// final List<Edge> edges = new ArrayList<Edge>();
//
// int offset = 0;
//
// // Store pivot pairs to restore afterwards
// final List<PivotPair> pivots = new ArrayList<PivotPair>();
//
// for (final Graph graph : graphs)
// {
// for (final Vertex vertex : graph.vertices())
// {
// final Vertex newVertex = new Vertex(vertices.size(), vertex.pt().x(), vertex.pt().y(), vertex.pt().z());
// newVertex.setTilingAndShape(vertex.basis(), vertex.shape());
// if (vertex.pivot() != null)
// pivots.add(new PivotPair(vertices.size(), vertex.pivot().id() + offset));
// vertices.add(newVertex);
// }
//
// for (final Edge edge : graph.edges())
// {
// final Vertex va = vertices.get(edge.vertexA().id() + offset);
// final Vertex vb = vertices.get(edge.vertexB().id() + offset);
// final Edge newEdge = new Edge(edges.size(), va, vb); //, edge.curved());
// newEdge.setTilingAndShape(edge.basis(), edge.shape());
// edges.add(newEdge);
// }
//
// offset += graph.vertices().size();
// }
//
// // Restore pivot vertices
// for (final PivotPair pivot : pivots)
// vertices.get(pivot.id).setPivot(vertices.get(pivot.pivotId));
//
// final Graph graph = new Graph(vertices, edges);
//
//// // Accumulate graphs together
//// final Graph graph = graphs[0];
//// for (int g = 1; g < graphs.length; g++)
//// {
//// graph.vertices().addAll(graphs[g].vertices());
//// graph.edges().addAll(graphs[g].edges());
//// graph.faces().addAll(graphs[g].faces());
////
////// for (final Vertex vertex : graphs[g].vertices())
////// graph.vertices().add(vertex);
//////
////// for (final Edge edge : graphs[g].edges())
////// graph.edges().add(edge);
//////
////// for (final Face face : graphs[g].faces())
////// graph.faces().add(face);
//// }
//// graph.reorder();
////
//// System.out.println("Graph has " + graph.vertices().size() + " vertices.");
//
// // Now connect new vertices to nearby neighbours, if desired
// if (connect)
// {
// final double threshold = 1.1 * graph.averageEdgeLength();
//
// for (final Vertex vertexA : graph.vertices())
// for (final Vertex vertexB : graph.vertices())
// {
// if (vertexA.id() == vertexB.id())
// continue;
//
// if (MathRoutines.distance(vertexA.pt2D(), vertexB.pt2D()) < threshold)
// graph.findOrAddEdge(vertexA.id(), vertexB.id());
// }
// graph.makeFaces(true);
//
// // **
// // ** No not reorder here! This breaks some graphs e.g. Mancala games.
// // **
// //graph.reorder();
// }
//
// graph.resetBasis();
// graph.resetShape();
//
// //System.out.println(graph);
//
// return graph;
for (int n = 1; n < graphFns.length; n++)
{
for (final Vertex vertex : graphs[n].vertices())
graphs[0].addVertex(vertex);
for (final Edge edge : graphs[n].edges())
graphs[0].addEdge(edge);
for (final Face face : graphs[n].faces())
graphs[0].addFace(face);
graphs[0].synchroniseIds();
}
// Now connect new vertices to nearby neighbours, if desired
if (connect)
{
final double threshold = 1.1 * graphs[0].averageEdgeLength();
for (final Vertex vertexA : graphs[0].vertices())
for (final Vertex vertexB : graphs[0].vertices())
{
if (vertexA.id() == vertexB.id())
continue;
if (MathRoutines.distance(vertexA.pt2D(), vertexB.pt2D()) < threshold)
graphs[0].findOrAddEdge(vertexA.id(), vertexB.id());
}
graphs[0].makeFaces(true);
// **
// ** No not reorder here! This breaks some graphs e.g. Mancala games.
// **
//graph.reorder();
}
graphs[0].resetBasis();
graphs[0].resetShape();
//System.out.println(graphs[0]);
return graphs[0];
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
for (final GraphFunction fn : graphFns)
if (!fn.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0;
for (final GraphFunction fn : graphFns)
flags |= fn.gameFlags(game);
return flags;
}
@Override
public void preprocess(final Game game)
{
// type = SiteType.use(type, game);
for (final GraphFunction fn : graphFns)
fn.preprocess(game);
if (isStatic())
precomputedGraph = eval(new Context(game, null),
(game.board().defaultSite() == SiteType.Vertex ? SiteType.Vertex : SiteType.Cell));
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(super.concepts(game));
// Commented because if some modifications are done to the graph we can not
// conclude about the tiling or the shape.
// for (final GraphFunction fn : graphFns)
// concepts.or(fn.concepts(game));
return concepts;
}
}
| 8,177 | 25.211538 | 110 | java |
Ludii | Ludii-master/Core/src/game/functions/graph/operators/package-info.java | /**
* This section contains the operations that can be performed on graphs that
* describe game boards. These typically involve transforming the graph,
* modifying it, or merging multiple sub-graphs.
*/
package game.functions.graph.operators;
| 249 | 34.714286 | 77 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/BaseIntArrayFunction.java | package game.functions.intArray;
import other.BaseLudeme;
/**
* Common functionality for IntArrayFunction - override where necessary.
*
* @author cambolbro
*/
public abstract class BaseIntArrayFunction extends BaseLudeme implements IntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
}
| 388 | 23.3125 | 89 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/IntArrayConstant.java | package game.functions.intArray;
import java.util.BitSet;
import annotations.Hide;
import game.Game;
import game.functions.ints.IntFunction;
import other.context.Context;
/**
* Sets a constant array of int values.
*
* @author cambolbro and Eric.Piette
*/
@Hide
public final class IntArrayConstant extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Constant value. */
private final IntFunction[] ints;
//-------------------------------------------------------------------------
/**
* Constant int array value.
*
* @param ints The values of the array.
*/
public IntArrayConstant
(
final IntFunction[] ints
)
{
this.ints = ints;
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
final int[] toReturn = new int[ints.length];
for (int i = 0; i < ints.length; i++)
{
final IntFunction intFunction = ints[i];
toReturn[i] = intFunction.eval(context);
}
return toReturn;
}
//-------------------------------------------------------------------------
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < ints.length; i++)
{
if (i > 0)
sb.append(",");
sb.append("" + ints[i]);
}
sb.append("]");
return sb.toString();
}
@Override
public boolean isStatic()
{
for (final IntFunction function : ints)
if (!function.isStatic())
return false;
return true;
}
@Override
public long gameFlags(final Game game)
{
long flags = 0l;
for (final IntFunction function : ints)
flags |= function.gameFlags(game);
return flags;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
for (final IntFunction function : ints)
concepts.or(function.concepts(game));
return concepts;
}
@Override
public void preprocess(final Game game)
{
for (final IntFunction function : ints)
function.preprocess(game);
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String englishString = "[";
for (final IntFunction i : ints)
englishString += i.toEnglish(game) + ",";
englishString = englishString.substring(0, englishString.length()-1);
englishString += "]";
return englishString;
}
//-------------------------------------------------------------------------
}
| 2,574 | 19.436508 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/IntArrayFunction.java | package game.functions.intArray;
import java.util.BitSet;
import game.Game;
import game.types.state.GameType;
import other.context.Context;
/**
* Returns an int array function.
*
* @author cambolbro
*/
// **
// ** Do not @Hide, or loses mapping in grammar!
// **
public interface IntArrayFunction extends GameType
{
/**
* @param context
* @return The result of applying this function to this trial.
*/
int[] eval(final Context context);
/**
* @param game The game.
* @return Accumulated flags corresponding to the game concepts.
*/
BitSet concepts(final Game game);
/**
* @return Accumulated flags corresponding to read data in EvalContext.
*/
BitSet readsEvalContextRecursive();
/**
* @return Accumulated flags corresponding to write data in EvalContext.
*/
BitSet writesEvalContextRecursive();
/**
* @param game The game.
* @return True if a required ludeme is missing.
*/
boolean missingRequirement(final Game game);
/**
* @param game The game.
* @return True if the ludeme can crash the game during its play.
*/
boolean willCrash(final Game game);
/**
* @param game
* @return This Function in English.
*/
String toEnglish(Game game);
}
| 1,208 | 18.819672 | 73 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/package-info.java | /**
* @chapter Integer array functions are ludemes that return an array of integer values,
* typically for processing by other ludemes.
*/
package game.functions.intArray;
| 185 | 30 | 88 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/array/Array.java | package game.functions.intArray.array;
import java.util.BitSet;
import game.Game;
import game.functions.intArray.BaseIntArrayFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import other.context.Context;
/**
* Converts a Region Function to an Int Array.
*
* @author Dennis Soemers and Eric.Piette
*/
public class Array extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Our region function */
private final RegionFunction region;
/** Our list of int functions. */
private final IntFunction[] ints;
//-------------------------------------------------------------------------
/**
* For creating an array from a region function.
*
* @param region The region function to be converted into an int array.
*
* @example (array (sites Board)))
*/
public Array(final RegionFunction region)
{
this.region = region;
ints = null;
}
/**
* For creating an array from a list of int functions.
*
* @param ints The int functions composing the array.
*
* @example (array {5 3 2})
*/
public Array(final IntFunction[] ints)
{
region = null;
this.ints = ints;
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
if(region != null)
return region.eval(context).sites();
else
{
final int[] array = new int[ints.length];
for(int i = 0; i < array.length; i++)
array[i] = ints[i].eval(context);
return array;
}
}
@Override
public long gameFlags(final Game game)
{
if(region != null)
return region.gameFlags(game);
else
{
long gameFlags = 0L;
for(final IntFunction intFn : ints)
gameFlags |= intFn.gameFlags(game);
return gameFlags;
}
}
@Override
public boolean isStatic()
{
if(region != null)
return region.isStatic();
else
{
for(final IntFunction intFn : ints)
if(!intFn.isStatic())
return false;
return true;
}
}
@Override
public void preprocess(final Game game)
{
if(region != null)
region.preprocess(game);
else
{
for(final IntFunction intFn : ints)
intFn.preprocess(game);
}
}
@Override
public BitSet concepts(final Game game)
{
if(region != null)
return region.concepts(game);
else
{
final BitSet concepts = new BitSet();
for(final IntFunction intFn : ints)
concepts.or(intFn.concepts(game));
return concepts;
}
}
@Override
public BitSet writesEvalContextRecursive()
{
if(region != null)
return region.writesEvalContextRecursive();
else
{
final BitSet writeEvalContext = new BitSet();
for(final IntFunction intFn : ints)
writeEvalContext.or(intFn.writesEvalContextRecursive());
return writeEvalContext;
}
}
@Override
public BitSet readsEvalContextRecursive()
{
if(region != null)
return region.readsEvalContextRecursive();
else
{
final BitSet readEvalContext = new BitSet();
for(final IntFunction intFn : ints)
readEvalContext.or(intFn.readsEvalContextRecursive());
return readEvalContext;
}
}
@Override
public boolean missingRequirement(final Game game)
{
if(region != null)
return region.missingRequirement(game);
else
{
for(final IntFunction intFn : ints)
if(intFn.missingRequirement(game))
return true;
return false;
}
}
@Override
public boolean willCrash(final Game game)
{
if(region != null)
return region.willCrash(game);
else
{
for(final IntFunction intFn : ints)
if(intFn.willCrash(game))
return true;
return false;
}
}
@Override
public String toEnglish(final Game game)
{
return "";
}
}
| 3,760 | 18.691099 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/array/package-info.java | /**
* Int array function to convert a region function to an int array.
*/
package game.functions.intArray.array;
| 115 | 22.2 | 67 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/iteraror/Team.java | package game.functions.intArray.iteraror;
import java.util.BitSet;
import game.Game;
import game.functions.intArray.BaseIntArrayFunction;
import other.concept.Concept;
import other.context.Context;
import other.context.EvalContextData;
/**
* Returns the team iterator.
*
* @author Eric.Piette
*/
public final class Team extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/**
* @example (team)
*/
public Team()
{
// Nothing to do.
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
return context.team();
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
final long flag = 0;
return flag;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.set(Concept.Team.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
return readsEvalContextFlat();
}
@Override
public BitSet readsEvalContextFlat()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.set(EvalContextData.Player.id(), true);
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
final boolean missingRequirement = false;
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
final boolean willCrash = false;
return willCrash;
}
@Override
public void preprocess(final Game game)
{
// Nothing to do.
}
}
| 1,875 | 17.392157 | 76 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/iteraror/package-info.java | /**
* Int array iterators.
*/
package game.functions.intArray.iteraror;
| 74 | 14 | 41 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/math/Difference.java | package game.functions.intArray.math;
import java.util.BitSet;
import annotations.Or;
import game.Game;
import game.functions.intArray.BaseIntArrayFunction;
import game.functions.intArray.IntArrayFunction;
import game.functions.ints.IntFunction;
import gnu.trove.list.array.TIntArrayList;
import other.context.Context;
/**
* Returns the difference between two arrays of integers, i.e. the elements in A
* that are not in B.
*
* @author Eric.Piette
*/
public final class Difference extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which region 1. */
private final IntArrayFunction source;
/** Which region 2. */
private final IntArrayFunction subtraction;
/** Which site. */
private final IntFunction intToRemove;
/** If we can, we'll precompute once and cache */
private int[] precomputedRegion = null;
//-------------------------------------------------------------------------
/**
* @param source The original array.
* @param subtraction The array to remove from the original array.
* @param intToRemove The integer to remove from the original array.
*
* @example (difference (values Remembered) 2)
*/
public Difference
(
final IntArrayFunction source,
@Or final IntArrayFunction subtraction,
@Or final IntFunction intToRemove
)
{
this.source = source;
int numNonNull = 0;
if (subtraction != null)
numNonNull++;
if (intToRemove != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Only one Or parameter must be non-null.");
this.intToRemove = intToRemove;
this.subtraction = subtraction;
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
if (precomputedRegion != null)
return precomputedRegion;
final int[] arraySource = source.eval(context);
final TIntArrayList sourcelist = new TIntArrayList(arraySource);
if (subtraction != null)
{
final int[] subSource = subtraction.eval(context);
final TIntArrayList subList = new TIntArrayList(subSource);
sourcelist.removeAll(subList);
}
else
{
final int integerToRemove = intToRemove.eval(context);
sourcelist.remove(integerToRemove);
}
return sourcelist.toArray();
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (!source.isStatic())
return false;
if (subtraction != null)
if (!subtraction.isStatic())
return false;
if (intToRemove != null && !intToRemove.isStatic())
return false;
return true;
}
@Override
public String toString()
{
return "Difference(" + source + "," + subtraction + ")";
}
@Override
public long gameFlags(final Game game)
{
long flag = 0;
flag |= source.gameFlags(game);
if (subtraction != null)
flag |= subtraction.gameFlags(game);
if (intToRemove != null)
flag |= intToRemove.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(source.concepts(game));
if(subtraction != null)
concepts.or(subtraction.concepts(game));
if (intToRemove != null)
concepts.or(intToRemove.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(source.writesEvalContextRecursive());
if (subtraction != null)
writeEvalContext.or(subtraction.writesEvalContextRecursive());
if (intToRemove != null)
writeEvalContext.or(intToRemove.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(source.readsEvalContextRecursive());
if (subtraction != null)
readEvalContext.or(subtraction.readsEvalContextRecursive());
if (intToRemove != null)
readEvalContext.or(intToRemove.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= source.missingRequirement(game);
if (subtraction != null)
missingRequirement |= subtraction.missingRequirement(game);
if (intToRemove != null)
missingRequirement |= intToRemove.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= source.willCrash(game);
if (subtraction != null)
willCrash |= subtraction.willCrash(game);
if (intToRemove != null)
willCrash |= intToRemove.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
source.preprocess(game);
if (subtraction != null)
subtraction.preprocess(game);
if (intToRemove != null)
intToRemove.preprocess(game);
if (isStatic())
{
final Context context = new Context(game, null);
final int[] arraySource = source.eval(context);
final TIntArrayList sourcelist = new TIntArrayList(arraySource);
if (subtraction != null)
{
final int[] subSource = subtraction.eval(context);
final TIntArrayList subList = new TIntArrayList(subSource);
sourcelist.removeAll(subList);
}
else
{
final int integerToRemove = intToRemove.eval(context);
sourcelist.remove(integerToRemove);
}
precomputedRegion = sourcelist.toArray();
}
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
String subtractionString = "";
if (subtraction != null)
subtractionString = subtraction.toEnglish(game);
else
subtractionString = intToRemove.toEnglish(game);
return "the difference between " + source.toEnglish(game) + " and " + subtractionString;
}
//-------------------------------------------------------------------------
}
| 6,053 | 23.119522 | 90 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/math/If.java | package game.functions.intArray.math;
import java.util.BitSet;
import annotations.Opt;
import game.Game;
import game.functions.booleans.BooleanConstant.FalseConstant;
import game.functions.booleans.BooleanFunction;
import game.functions.intArray.BaseIntArrayFunction;
import game.functions.intArray.IntArrayConstant;
import game.functions.intArray.IntArrayFunction;
import game.functions.ints.IntFunction;
import other.concept.Concept;
import other.context.Context;
/**
* Returns an array when the condition is satisfied and another when it is not.
*
* @author Eric.Piette
*/
public final class If extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Condition to check. */
private final BooleanFunction condition;
/** Value returned if the condition is true. */
private final IntArrayFunction ok;
/** Value returned if the condition is false. */
private final IntArrayFunction notOk;
//-------------------------------------------------------------------------
/**
* @param cond The condition to satisfy.
* @param ok The array returned when the condition is satisfied.
* @param notOk The array returned when the condition is not satisfied.
*
* @example (if (is Mover P1) (values Remembered "RememberedP1") (values Remembered "RememberedP2"))
*/
public If
(
final BooleanFunction cond,
final IntArrayFunction ok,
@Opt final IntArrayFunction notOk
)
{
this.condition = cond;
this.ok = ok;
this.notOk = (notOk == null) ? new IntArrayConstant(new IntFunction[0]) : notOk;
}
//-------------------------------------------------------------------------
@Override
public final int[] eval(final Context context)
{
if (condition.eval(context))
return this.ok.eval(context);
else
return this.notOk.eval(context);
}
@Override
public boolean isStatic()
{
return condition.isStatic() && ok.isStatic() && notOk.isStatic();
}
@Override
public long gameFlags(final Game game)
{
return condition.gameFlags(game) | ok.gameFlags(game) | notOk.gameFlags(game);
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(condition.concepts(game));
concepts.or(ok.concepts(game));
concepts.or(notOk.concepts(game));
concepts.set(Concept.ConditionalStatement.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.or(condition.writesEvalContextRecursive());
writeEvalContext.or(ok.writesEvalContextRecursive());
writeEvalContext.or(notOk.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(condition.readsEvalContextRecursive());
readEvalContext.or(ok.readsEvalContextRecursive());
readEvalContext.or(notOk.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (condition instanceof FalseConstant)
{
game.addRequirementToReport("One of the condition of a (if ...) ludeme is \"false\" which is wrong.");
missingRequirement = true;
}
missingRequirement |= condition.missingRequirement(game);
missingRequirement |= ok.missingRequirement(game);
missingRequirement |= notOk.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= condition.willCrash(game);
willCrash |= ok.willCrash(game);
willCrash |= notOk.willCrash(game);
return willCrash;
}
@Override
public void preprocess(final Game game)
{
condition.preprocess(game);
ok.preprocess(game);
notOk.preprocess(game);
}
}
| 3,912 | 25.619048 | 105 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/math/Intersection.java | package game.functions.intArray.math;
import java.util.BitSet;
import game.Game;
import game.functions.intArray.BaseIntArrayFunction;
import game.functions.intArray.IntArrayFunction;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
/**
* Returns the intersection of many regions.
*
* @author Eric.Piette and cambolbro
*/
public class Intersection extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which array 1. */
private final IntArrayFunction array1;
/** Which array 2. */
private final IntArrayFunction array2;
/** Which array. */
private final IntArrayFunction[] arrays;
/** If we can, we'll precompute once and cache */
private int[] precomputedArray = null;
//-------------------------------------------------------------------------
/**
* For the intersection of two arrays.
*
* @param array1 The first array.
* @param array2 The second array.
* @example (intersection (values Remembered "Earth") (values Remembered "Sea"))
*/
public Intersection
(
final IntArrayFunction array1,
final IntArrayFunction array2
)
{
this.array1 = array1;
this.array2 = array2;
arrays = null;
}
/**
* For the intersection of many arrays.
*
* @param arrays The different arrays.
*
* @example (intersection {(values Remembered "Earth") (values Remembered "Sea")
* (values Remembered "Sky")})
*/
public Intersection(final IntArrayFunction[] arrays)
{
array1 = null;
array2 = null;
this.arrays = arrays;
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
if (precomputedArray != null)
return precomputedArray;
if (arrays == null)
{
final TIntArrayList values1 = new TIntArrayList(array1.eval(context));
final TIntArrayList values2 = new TIntArrayList(array2.eval(context));
for (int i = values2.size() - 1; i >= 0 ; i--)
{
final int value = values2.get(i);
if (!values1.contains(value))
values2.removeAt(i);
}
return values2.toArray();
}
else
{
if (arrays.length == 0)
return new int[0];
final TIntArrayList values1 = new TIntArrayList(arrays[0].eval(context));
for (int i = 1; i < arrays.length; i++)
{
final TIntArrayList values2 = new TIntArrayList(arrays[i].eval(context));
for (int j = values1.size() - 1; j >= 0 ; j--)
{
final int value = values1.get(j);
if (!values2.contains(value))
values1.removeAt(j);
}
}
return values1.toArray();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (arrays == null)
{
return array1.isStatic() && array2.isStatic();
}
else
{
for (final IntArrayFunction array : arrays)
if (!array.isStatic())
return false;
return true;
}
}
@Override
public long gameFlags(final Game game)
{
if (arrays == null)
{
return array1.gameFlags(game) | array2.gameFlags(game);
}
else
{
long gameFlags = 0;
for (final IntArrayFunction array : arrays)
gameFlags |= array.gameFlags(game);
return gameFlags;
}
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (arrays == null)
{
concepts.or(array1.concepts(game));
concepts.or(array2.concepts(game));
}
else
{
for (final IntArrayFunction array : arrays)
concepts.or(array.concepts(game));
}
concepts.set(Concept.Union.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (arrays == null)
{
writeEvalContext.or(array1.writesEvalContextRecursive());
writeEvalContext.or(array2.writesEvalContextRecursive());
}
else
{
for (final IntArrayFunction array : arrays)
writeEvalContext.or(array.writesEvalContextRecursive());
}
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (arrays == null)
{
readEvalContext.or(array1.readsEvalContextRecursive());
readEvalContext.or(array2.readsEvalContextRecursive());
}
else
{
for (final IntArrayFunction array : arrays)
readEvalContext.or(array.readsEvalContextRecursive());
}
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (arrays == null)
{
missingRequirement |= array1.missingRequirement(game);
missingRequirement |= array2.missingRequirement(game);
}
else
{
for (final IntArrayFunction array : arrays)
missingRequirement |= array.missingRequirement(game);
}
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (arrays == null)
{
willCrash |= array1.willCrash(game);
willCrash |= array2.willCrash(game);
}
else
{
for (final IntArrayFunction array : arrays)
willCrash |= array.willCrash(game);
}
return willCrash;
}
@Override
public void preprocess(final Game game)
{
if (arrays == null)
{
array1.preprocess(game);
array2.preprocess(game);
}
else
{
for (final IntArrayFunction array : arrays)
array.preprocess(game);
}
if (isStatic())
{
precomputedArray = eval(new Context(game, null));
}
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
if (arrays != null)
{
String arrayString = "[";
for (final IntArrayFunction i : arrays)
arrayString += i.toEnglish(game) + ",";
arrayString = arrayString.substring(0,arrayString.length()-1) + "]";
return "the intersectin of all arrays in " + arrayString;
}
else
{
return "the intersection of " + array1.toEnglish(game) + " and " + array2.toEnglish(game);
}
}
//-------------------------------------------------------------------------
}
| 6,137 | 21.32 | 93 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/math/Results.java | package game.functions.intArray.math;
import java.util.BitSet;
import annotations.Name;
import annotations.Or;
import annotations.Or2;
import game.Game;
import game.functions.intArray.BaseIntArrayFunction;
import game.functions.ints.IntFunction;
import game.functions.region.RegionFunction;
import gnu.trove.list.array.TIntArrayList;
import other.IntArrayFromRegion;
import other.context.Context;
import other.context.EvalContextData;
/**
* Returns an array of all the results of the function for each site 'from' to each site 'to'.
*
* @author Eric.Piette
*/
public final class Results extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which region 1. */
private final IntArrayFromRegion regionFromFn;
/** Which region 2. */
private final IntArrayFromRegion regionToFn;
/** Which function. */
private final IntFunction functionFn;
//-------------------------------------------------------------------------
/**
* @param from The 'from' site.
* @param From The 'from' region.
* @param to The 'to' site.
* @param To The 'to' region.
* @param function The function to compute for each site 'from' and each site
* 'to'.
* @example (results from:(last To) to:(sites LineOfSight at:(from) All) (count
* Steps All (from) (to)))
*/
public Results
(
@Name @Or final IntFunction from,
@Name @Or final RegionFunction From,
@Name @Or2 final IntFunction to,
@Name @Or2 final RegionFunction To,
final IntFunction function
)
{
int numNonNull = 0;
if (from != null)
numNonNull++;
if (From != null)
numNonNull++;
if (numNonNull != 1)
throw new IllegalArgumentException("Only one Or parameter must be non-null.");
int numNonNull2 = 0;
if (to != null)
numNonNull2++;
if (To != null)
numNonNull2++;
if (numNonNull2 != 1)
throw new IllegalArgumentException("Only one Or2 parameter must be non-null.");
functionFn = function;
regionFromFn = new IntArrayFromRegion(from, From);
regionToFn = new IntArrayFromRegion(to, To);
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
final TIntArrayList resultList = new TIntArrayList();
final int[] sitesFrom = regionFromFn.eval(context);
final int originFrom = context.from();
final int originTo = context.to();
for (final int from : sitesFrom)
{
context.setFrom(from);
final int[] sitesTo = regionToFn.eval(context);
for (final int to : sitesTo)
{
context.setTo(to);
resultList.add(functionFn.eval(context));
}
}
context.setFrom(originFrom);
context.setTo(originTo);
return resultList.toArray();
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
return false;
}
@Override
public long gameFlags(final Game game)
{
long flag = 0;
flag |= regionFromFn.gameFlags(game);
flag |= regionToFn.gameFlags(game);
flag |= functionFn.gameFlags(game);
return flag;
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
concepts.or(regionFromFn.concepts(game));
concepts.or(regionToFn.concepts(game));
concepts.or(functionFn.concepts(game));
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = writesEvalContextFlat();
writeEvalContext.or(regionFromFn.writesEvalContextRecursive());
writeEvalContext.or(regionToFn.writesEvalContextRecursive());
writeEvalContext.or(functionFn.writesEvalContextRecursive());
return writeEvalContext;
}
@Override
public BitSet writesEvalContextFlat()
{
final BitSet writeEvalContext = new BitSet();
writeEvalContext.set(EvalContextData.To.id(), true);
writeEvalContext.set(EvalContextData.From.id(), true);
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
readEvalContext.or(regionFromFn.readsEvalContextRecursive());
readEvalContext.or(regionToFn.readsEvalContextRecursive());
readEvalContext.or(functionFn.readsEvalContextRecursive());
return readEvalContext;
}
@Override
public void preprocess(final Game game)
{
regionFromFn.preprocess(game);
regionToFn.preprocess(game);
functionFn.preprocess(game);
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
missingRequirement |= regionFromFn.missingRequirement(game);
missingRequirement |= regionToFn.missingRequirement(game);
missingRequirement |= functionFn.missingRequirement(game);
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
willCrash |= regionFromFn.willCrash(game);
willCrash |= regionToFn.willCrash(game);
willCrash |= functionFn.willCrash(game);
return willCrash;
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
return "the results of applying " + functionFn.toEnglish(game) + " from " + regionFromFn.toEnglish(game) + " to " + regionToFn.toEnglish(game);
}
//-------------------------------------------------------------------------
}
| 5,428 | 25.612745 | 146 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/math/Union.java | package game.functions.intArray.math;
import java.util.BitSet;
import game.Game;
import game.functions.intArray.BaseIntArrayFunction;
import game.functions.intArray.IntArrayFunction;
import gnu.trove.list.array.TIntArrayList;
import other.concept.Concept;
import other.context.Context;
/**
* Merges many integer arrays into one.
*
* @author Eric.Piette
*/
public final class Union extends BaseIntArrayFunction
{
private static final long serialVersionUID = 1L;
//-------------------------------------------------------------------------
/** Which array 1. */
private final IntArrayFunction array1;
/** Which array 2. */
private final IntArrayFunction array2;
/** Which arrays. */
private final IntArrayFunction[] arrays;
/** If we can, we'll precompute once and cache */
private int[] precomputedArray = null;
//-------------------------------------------------------------------------
/**
* For the union of two arrays.
*
* @param array1 The first array.
* @param array2 The second array.
*
* @example (union (values Remembered "Forest") (values Remembered "Sea"))
*/
public Union
(
final IntArrayFunction array1,
final IntArrayFunction array2
)
{
this.array1 = array1;
this.array2 = array2;
arrays = null;
}
/**
* For the union of many arrays.
*
* @param arrays The different arrays.
*
* @example (union {(values Remembered "Forest") (values Remembered "Sea")
* (values Remembered "Sky")})
*/
public Union(final IntArrayFunction[] arrays)
{
array1 = null;
array2 = null;
this.arrays = arrays;
}
//-------------------------------------------------------------------------
@Override
public int[] eval(final Context context)
{
if (precomputedArray != null)
return precomputedArray;
if (arrays == null)
{
final TIntArrayList values1 = new TIntArrayList(array1.eval(context));
final int[] values2 = array2.eval(context);
for (int i = 0; i < values2.length; i++)
{
final int value = values2[i];
if (!values1.contains(value))
values1.add(value);
}
return values1.toArray();
}
else
{
if (arrays.length == 0)
return new int[0];
final TIntArrayList values1 = new TIntArrayList(arrays[0].eval(context));
for (int i = 1; i < arrays.length; i++)
{
final int[] values2 = arrays[i].eval(context);
for (int j = 0; j < values2.length; j++)
{
final int value = values2[j];
if (!values1.contains(value))
values1.add(value);
}
}
return values1.toArray();
}
}
//-------------------------------------------------------------------------
@Override
public boolean isStatic()
{
if (arrays == null)
{
return array1.isStatic() && array2.isStatic();
}
else
{
for (final IntArrayFunction array : arrays)
if (!array.isStatic())
return false;
return true;
}
}
@Override
public long gameFlags(final Game game)
{
if (arrays == null)
{
return array1.gameFlags(game) | array2.gameFlags(game);
}
else
{
long gameFlags = 0;
for (final IntArrayFunction array : arrays)
gameFlags |= array.gameFlags(game);
return gameFlags;
}
}
@Override
public BitSet concepts(final Game game)
{
final BitSet concepts = new BitSet();
if (arrays == null)
{
concepts.or(array1.concepts(game));
concepts.or(array2.concepts(game));
}
else
{
for (final IntArrayFunction array : arrays)
concepts.or(array.concepts(game));
}
concepts.set(Concept.Union.id(), true);
return concepts;
}
@Override
public BitSet writesEvalContextRecursive()
{
final BitSet writeEvalContext = new BitSet();
if (arrays == null)
{
writeEvalContext.or(array1.writesEvalContextRecursive());
writeEvalContext.or(array2.writesEvalContextRecursive());
}
else
{
for (final IntArrayFunction array : arrays)
writeEvalContext.or(array.writesEvalContextRecursive());
}
return writeEvalContext;
}
@Override
public BitSet readsEvalContextRecursive()
{
final BitSet readEvalContext = new BitSet();
if (arrays == null)
{
readEvalContext.or(array1.readsEvalContextRecursive());
readEvalContext.or(array2.readsEvalContextRecursive());
}
else
{
for (final IntArrayFunction array : arrays)
readEvalContext.or(array.readsEvalContextRecursive());
}
return readEvalContext;
}
@Override
public boolean missingRequirement(final Game game)
{
boolean missingRequirement = false;
if (arrays == null)
{
missingRequirement |= array1.missingRequirement(game);
missingRequirement |= array2.missingRequirement(game);
}
else
{
for (final IntArrayFunction array : arrays)
missingRequirement |= array.missingRequirement(game);
}
return missingRequirement;
}
@Override
public boolean willCrash(final Game game)
{
boolean willCrash = false;
if (arrays == null)
{
willCrash |= array1.willCrash(game);
willCrash |= array2.willCrash(game);
}
else
{
for (final IntArrayFunction array : arrays)
willCrash |= array.willCrash(game);
}
return willCrash;
}
@Override
public void preprocess(final Game game)
{
if (arrays == null)
{
array1.preprocess(game);
array2.preprocess(game);
}
else
{
for (final IntArrayFunction array : arrays)
array.preprocess(game);
}
if (isStatic())
{
precomputedArray = eval(new Context(game, null));
}
}
//-------------------------------------------------------------------------
@Override
public String toEnglish(final Game game)
{
if (arrays != null)
{
String arrayString = "[";
for (final IntArrayFunction i : arrays)
arrayString += i.toEnglish(game) + ",";
arrayString = arrayString.substring(0,arrayString.length()-1) + "]";
return "the union of all arrays in " + arrayString;
}
else
{
return "the union of " + array1.toEnglish(game) + " and " + array2.toEnglish(game);
}
}
//-------------------------------------------------------------------------
}
| 5,990 | 20.785455 | 86 | java |
Ludii | Ludii-master/Core/src/game/functions/intArray/math/package-info.java | /**
* Math int array functions return an of integer values based on given inputs.
*/
package game.functions.intArray.math;
| 125 | 24.2 | 78 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.