Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

feat: add clipping box #338

Merged
merged 18 commits into from
Nov 16, 2022
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions src/components/molecules/Visualizer/Engine/Cesium/Box/Side.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import {
Axis,
CallbackProperty,
Cartesian2,
Cartesian3,
Color,
Matrix4,
Plane as CesiumPlane,
PositionProperty,
TranslationRotationScale,
} from "cesium";
import { useMemo, FC, memo } from "react";
import { Entity, PlaneGraphics } from "resium";

import { BoxStyle } from ".";

// ref: https://github.com/TerriaJS/terriajs/blob/cad62a45cbee98c7561625458bec3a48510f6cbc/lib/Models/BoxDrawing.ts#L1446-L1461
function setPlaneDimensions(
boxDimensions: Cartesian3,
planeNormalAxis: Axis,
planeDimensions: Cartesian2,
) {
if (planeNormalAxis === Axis.X) {
planeDimensions.x = boxDimensions.y;
planeDimensions.y = boxDimensions.z;
} else if (planeNormalAxis === Axis.Y) {
planeDimensions.x = boxDimensions.x;
planeDimensions.y = boxDimensions.z;
} else if (planeNormalAxis === Axis.Z) {
planeDimensions.x = boxDimensions.x;
planeDimensions.y = boxDimensions.y;
}
}

export const Side: FC<{
id: string;
planeLocal: CesiumPlane;
trs: TranslationRotationScale;
style: BoxStyle<Color>;
}> = memo(function SidePresenter({ id, planeLocal, style, trs }) {
const normalAxis = planeLocal.normal.x ? Axis.X : planeLocal.normal.y ? Axis.Y : Axis.Z;
const cbRef = useMemo(
() => new CallbackProperty(() => trs.translation, false) as unknown as PositionProperty,
[trs],
);
const [plane, dimension] = useMemo(() => {
const dimension = new Cartesian3();
setPlaneDimensions(trs.scale, normalAxis, dimension);
const scratchScaleMatrix = new Matrix4();
const scaleMatrix = Matrix4.fromScale(trs.scale, scratchScaleMatrix);
const plane = CesiumPlane.transform(
planeLocal,
scaleMatrix,
new CesiumPlane(Cartesian3.UNIT_Z, 0),
);
return [plane, dimension];
}, [trs, normalAxis, planeLocal]);

return (
<Entity id={id} position={cbRef}>
<PlaneGraphics
plane={plane}
dimensions={dimension}
fill={style.fill}
outline={style.outline}
material={style.fillColor}
outlineColor={style.outlineColor}
outlineWidth={style.outlineWidth}
/>
</Entity>
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Meta, Story } from "@storybook/react";

import { V, location } from "../storybook";

import Box, { Props } from ".";

export default {
title: "molecules/Visualizer/Engine/Cesium/Box",
component: Box,
} as Meta;

export const Default: Story<Props> = args => (
<V location={location}>
<Box {...args} />
</V>
);

Default.args = {
layer: {
id: "",
property: {
default: {
fillColor: "rgba(0, 0, 0, 0.5)",
location,
height: location.height,
dimensions: {
x: 1000,
y: 1000,
z: 1000,
},
},
},
isVisible: true,
},
};
102 changes: 102 additions & 0 deletions src/components/molecules/Visualizer/Engine/Cesium/Box/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { Cartesian3, Color, Plane as CesiumPlane, TranslationRotationScale } from "cesium";
import React, { useMemo, useEffect, memo, useState } from "react";

import { LatLng, toColor } from "@reearth/util/value";

import type { Props as PrimitiveProps } from "../../../Primitive";

import { Side } from "./Side";

export type Props = PrimitiveProps<Property>;

export type BoxStyle<C = Color | string> = {
fillColor?: C;
outlineColor?: C;
outlineWidth?: number;
fill?: boolean;
outline?: boolean;
};

export type Property = {
default?: {
position?: LatLng;
location?: LatLng;
height?: number;
dimensions?: {
x: number;
y: number;
z: number;
};
} & BoxStyle<string>;
};
keiya01 marked this conversation as resolved.
Show resolved Hide resolved

// The 6 box sides defined as planes in local coordinate space.
// ref: https://github.com/TerriaJS/terriajs/blob/cad62a45cbee98c7561625458bec3a48510f6cbc/lib/Models/BoxDrawing.ts#L161-L169
const SIDE_PLANES: readonly CesiumPlane[] = [
new CesiumPlane(new Cartesian3(0, 0, 1), 0.5),
new CesiumPlane(new Cartesian3(0, 0, -1), 0.5),
new CesiumPlane(new Cartesian3(0, 1, 0), 0.5),
new CesiumPlane(new Cartesian3(0, -1, 0), 0.5),
new CesiumPlane(new Cartesian3(1, 0, 0), 0.5),
new CesiumPlane(new Cartesian3(-1, 0, 0), 0.5),
];

// This is used for plane ID.
// We can use this name, for example you want to move the box when front plane is dragged.
const SIDE_PLANE_NAMES = ["bottom", "top", "front", "back", "left", "right"];

const updateTrs = (trs: TranslationRotationScale, property: Property | undefined) => {
const { position, location, height, dimensions } = property?.default ?? {};

const pos = position || location;
const translation = pos ? Cartesian3.fromDegrees(pos.lng, pos.lat, height ?? 0) : undefined;
if (translation) {
Cartesian3.clone(translation, trs.translation);
}

// Quaternion.clone(trs.rotation, this.trs.rotation);

Cartesian3.clone(
new Cartesian3(dimensions?.x || 100, dimensions?.y || 100, dimensions?.z || 100),
trs.scale,
);

return trs;
};

const Box: React.FC<PrimitiveProps<Property>> = memo(function BoxPresenter({ layer }) {
KaWaite marked this conversation as resolved.
Show resolved Hide resolved
const { id, isVisible, property } = layer ?? {};
const { fillColor, outlineColor, outlineWidth, fill, outline } = property?.default ?? {};

const [trs] = useState(() => updateTrs(new TranslationRotationScale(), property));
useEffect(() => {
updateTrs(trs, property);
}, [property, trs]);

const style: BoxStyle<Color> = useMemo(
() => ({
fillColor: toColor(fillColor),
outlineColor: toColor(outlineColor),
outlineWidth,
fill,
outline,
}),
[fillColor, outlineColor, outlineWidth, fill, outline],
);

return !isVisible ? null : (
<>
{SIDE_PLANES.map((plane, i) => (
<Side
key={`${id}-plane-${SIDE_PLANE_NAMES[i]}`}
id={`${id}-plane-${SIDE_PLANE_NAMES[i]}`}
planeLocal={plane}
style={style}
trs={trs}
/>
))}
</>
);
KaWaite marked this conversation as resolved.
Show resolved Hide resolved
});

export default Box;
110 changes: 105 additions & 5 deletions src/components/molecules/Visualizer/Engine/Cesium/Tileset/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
import { Cesium3DTileset as Cesium3DTilesetType, Cesium3DTileStyle, IonResource } from "cesium";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Cartesian3,
Cesium3DTileset as Cesium3DTilesetType,
Cesium3DTileStyle,
ClippingPlaneCollection as CesiumClippingPlaneCollection,
HeadingPitchRoll,
IonResource,
Matrix3,
Matrix4,
Transforms,
} from "cesium";
import ClippingPlane from "cesium/Source/Scene/ClippingPlane";
import { FC, useCallback, useEffect, useMemo, useRef, useState, memo } from "react";
import { Cesium3DTileset, CesiumComponentRef, useCesium } from "resium";

import { ClippingPlaneCollection, toColor } from "@reearth/util/value";

import type { Props as PrimitiveProps } from "../../../Primitive";
import { shadowMode, layerIdField } from "../common";

Expand All @@ -13,25 +26,109 @@ export type Property = {
tileset?: string;
styleUrl?: string;
shadows?: "disabled" | "enabled" | "cast_only" | "receive_only";
edgeWidth?: number;
edgeColor?: string;
clippingPlaneCollection?: ClippingPlaneCollection;
keiya01 marked this conversation as resolved.
Show resolved Hide resolved
};
};

export default function Tileset({ layer }: PrimitiveProps<Property>): JSX.Element | null {
const Tileset: FC<PrimitiveProps<Property>> = memo(function TilesetPresenter({ layer }) {
const { viewer } = useCesium();
const { isVisible, property } = layer ?? {};
const { sourceType, tileset, styleUrl, shadows } =
const { sourceType, tileset, styleUrl, shadows, edgeColor, edgeWidth, clippingPlaneCollection } =
(property as Property | undefined)?.default ?? {};
const {
dimensions: planeDimensions,
lat,
lng,
height,
heading,
roll,
pitch,
planes: _planes,
} = clippingPlaneCollection || {};
const [style, setStyle] = useState<Cesium3DTileStyle>();
const prevPlanes = useRef(_planes);
const planes = useMemo(() => {
if (
!prevPlanes.current?.length ||
!prevPlanes.current?.every(
(p, i) =>
p.normal?.x === _planes?.[i].normal?.x &&
p.normal?.y === _planes?.[i].normal?.y &&
p.normal?.z === _planes?.[i].normal?.z &&
p.distance === _planes?.[i].distance,
)
) {
prevPlanes.current = _planes;
}
return prevPlanes.current;
}, [_planes]);
// Create immutable object
const [clippingPlanes] = useState(
() =>
new CesiumClippingPlaneCollection({
planes: planes?.map(
plane =>
new ClippingPlane(
new Cartesian3(plane.normal?.x, plane.normal?.y, plane.normal?.z),
(plane.distance || 0) * -1,
),
),
edgeWidth: edgeWidth,
edgeColor: toColor(edgeColor),
}),
);
const tilesetRef = useRef<Cesium3DTilesetType>();

const ref = useCallback(
(tileset: CesiumComponentRef<Cesium3DTilesetType> | null) => {
if (layer?.id && tileset?.cesiumElement) {
(tileset?.cesiumElement as any)[layerIdField] = layer.id;
}
tilesetRef.current = tileset?.cesiumElement;
},
[layer?.id],
);

useEffect(() => {
const prepareClippingPlanes = async () => {
if (!tilesetRef.current) {
return;
}

await tilesetRef.current?.readyPromise;

const clippingPlanesOriginMatrix = Transforms.eastNorthUpToFixedFrame(
tilesetRef.current.boundingSphere.center.clone(),
);

const dimensions = new Cartesian3(
planeDimensions?.width || 100,
planeDimensions?.length || 100,
planeDimensions?.height || 100,
);

const position = Cartesian3.fromDegrees(lng || 0, lat || 0, height);

const hpr =
heading && pitch && roll ? HeadingPitchRoll.fromDegrees(heading, pitch, roll) : undefined;
const boxTransform = Matrix4.multiply(
hpr
? Matrix4.fromRotationTranslation(Matrix3.fromHeadingPitchRoll(hpr), position)
: Transforms.eastNorthUpToFixedFrame(position),
Matrix4.fromScale(dimensions, new Matrix4()),
new Matrix4(),
);

const inverseOriginalModelMatrix = Matrix4.inverse(clippingPlanesOriginMatrix, new Matrix4());

Matrix4.multiply(inverseOriginalModelMatrix, boxTransform, clippingPlanes.modelMatrix);
keiya01 marked this conversation as resolved.
Show resolved Hide resolved
};

prepareClippingPlanes();
}, [planeDimensions?.width, planeDimensions?.length, planeDimensions?.height, lng, lat, height, heading, pitch, roll, clippingPlanes.modelMatrix]);

useEffect(() => {
if (!styleUrl) {
setStyle(undefined);
Expand Down Expand Up @@ -59,8 +156,11 @@ export default function Tileset({ layer }: PrimitiveProps<Property>): JSX.Elemen
style={style}
shadows={shadowMode(shadows)}
onReady={_debugFlight ? t => viewer?.zoomTo(t) : undefined}
clippingPlanes={clippingPlanes}
/>
);
}
});

const _debugFlight = false;

export default Tileset;
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Component } from "../../Primitive";

import Box from "./Box";
import Ellipsoid from "./Ellipsoid";
import Marker from "./Marker";
import Model from "./Model";
Expand All @@ -16,6 +17,7 @@ const builtin: Record<string, Component> = {
"reearth/polygon": Polygon,
"reearth/rect": Rect,
"reearth/ellipsoid": Ellipsoid,
"reearth/box": Box,
"reearth/photooverlay": PhotoOverlay,
"reearth/resource": Resource,
"reearth/model": Model,
Expand Down
7 changes: 7 additions & 0 deletions src/components/molecules/Visualizer/Engine/Cesium/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
sampleTerrainMostDetailed,
Ray,
IntersectionTests,
Transforms,
} from "cesium";
import { useCallback, MutableRefObject } from "react";

Expand Down Expand Up @@ -292,6 +293,12 @@ export const lookAt = (
};
};

export const lookAtWithoutAnimation = (scene: Scene) => {
const camera = scene.camera;
const frame = Transforms.eastNorthUpToFixedFrame(camera.positionWC, scene.globe.ellipsoid);
camera.lookAtTransform(frame);
};

export const animateFOV = ({
fov,
camera,
Expand Down
Loading