Skip to content

Commit

Permalink
feat: start hitTest
Browse files Browse the repository at this point in the history
  • Loading branch information
F-star committed May 14, 2024
1 parent 4c7f6ad commit 181fa96
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 23 deletions.
22 changes: 11 additions & 11 deletions packages/core/src/graphs/star.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { parseHexToRGBA, parseRGBAStr } from '@suika/common';
import { getStar } from '@suika/geo';
import { type Optional } from 'pixi.js';
import { getStar, isPointInPolygon } from '@suika/geo';
import { Matrix, type Optional } from 'pixi.js';

import { type ImgManager } from '../Img_manager';
import { type IPaint, PaintType } from '../paint';
Expand Down Expand Up @@ -147,13 +147,13 @@ export class Star extends Graph<StarAttrs> {
super.updateAttrs(partialAttrs, options);
}

// override hitTest(x: number, y: number, _padding?: number) {
// // TODO: solve padding
// const tf = new Matrix(...this.attrs.transform);
// const point = tf.applyInverse({ x, y });
// return isPointInConvexPolygon(
// getStar(this.getSize(), this.attrs.count),
// point,
// );
// }
override hitTest(x: number, y: number, _padding?: number) {
// TODO: solve padding
const tf = new Matrix(...this.attrs.transform);
const point = tf.applyInverse({ x, y });
return isPointInPolygon(
getStar(this.getSize(), this.attrs.count, this.attrs.starInnerScale),
point,
);
}
}
39 changes: 27 additions & 12 deletions packages/geo/src/geo/geo_polygon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,36 @@ export const isPointInConvexPolygon = (polygon: IPoint[], point: IPoint) => {
return true;
};

// TODO: 射线法
export const isPointInPolygon = (polygon: IPoint[], point: IPoint) => {
/**
* 点向右侧射出
*/
// const count = 0;
export const isPointInPolygon = (polygon: IPoint[], pt: IPoint): boolean => {
let count = 0;
for (let i = 0; i < polygon.length; i++) {
const start = polygon[i];
const end = polygon[(i + 1) % polygon.length];
let a = polygon[i];
let b = polygon[(i + 1) % polygon.length];

if (start.x < point.x && end.x < point.x) {
continue;
if (a.y > b.y) {
[a, b] = [b, a];
}

if (a.y <= pt.y && b.y > pt.y) {
const crossProduct = cp(a, b, pt);
if (crossProduct === 0) {
return true;
} else if (crossProduct > 0) {
count++;
}
}
// if (start.y >)
}

return false;
return count % 2 === 1;
};

/**
* cross product of "p1->p2" and "p1->p3"
*/
const cp = (p1: IPoint, p2: IPoint, p3: IPoint): number => {
const x1 = p2.x - p1.x;
const y1 = p2.y - p1.y;
const x2 = p3.x - p1.x;
const y2 = p3.y - p1.y;
return x1 * y2 - x2 * y1;
};

0 comments on commit 181fa96

Please sign in to comment.