|
R/ |
345 | 147 | 0 | 147 | 0.0 | 0.00% |
|
R/ |
177 | 82 | 0 | 82 | 0.0 | 0.00% |
|
R/ |
50 | 27 | 0 | 27 | 0.0 | 0.00% |
|
R/ |
68 | 11 | 0 | 11 | 0.0 | 0.00% |
|
R/ |
20 | 6 | 0 | 6 | 0.0 | 0.00% |
|
R/ |
7 | 3 | 0 | 3 | 0.0 | 0.00% |
|
R/ |
35 | 12 | 3 | 9 | 85.4 | 25.00% |
|
R/ |
1089 | 466 | 163 | 303 | 50.2 | 34.98% |
|
R/ |
311 | 181 | 122 | 59 | 70.1 | 67.40% |
|
R/ |
179 | 72 | 55 | 17 | 21.2 | 76.39% |
|
src/ |
155 | 59 | 52 | 7 | 10375.2 | 88.14% |
|
R/ |
39 | 19 | 17 | 2 | 838.7 | 89.47% |
|
R/ |
22 | 10 | 9 | 1 | 52.0 | 90.00% |
|
R/ |
233 | 149 | 138 | 11 | 1131.5 | 92.62% |
|
src/ |
442 | 243 | 227 | 16 | 296934.6 | 93.42% |
|
R/ |
64 | 42 | 40 | 2 | 126.3 | 95.24% |
|
src/ |
212 | 103 | 100 | 2 | 321111.6 | 97.09% |
|
R/ |
102 | 44 | 44 | 0 | 26.0 | 100.00% |
|
R/ |
46 | 22 | 22 | 0 | 1429.3 | 100.00% |
|
R/ |
30 | 12 | 12 | 0 | 4688.4 | 100.00% |
|
R/ |
16 | 11 | 11 | 0 | 203.0 | 100.00% |
|
R/ |
20 | 7 | 7 | 0 | 139.0 | 100.00% |
|
R/ |
16 | 4 | 4 | 0 | 417.0 | 100.00% |
|
R/ |
15 | 4 | 4 | 0 | 118.0 | 100.00% |
|
src/ |
11 | 4 | 4 | 0 | 178141.5 | 100.00% |
|
R/ |
15 | 3 | 3 | 0 | 321.0 | 100.00% |
| Total | 3719 | 1743 | 1037 | 705 | 61318.7 | 59.50% |
| 1 | #' Get Face IDs | |
| 2 | #' | |
| 3 | #' @param ss | |
| 4 | #' | |
| 5 | #' @keywords internal | |
| 6 | get_n_cores = function() { | |
| 7 | 65x | n_cores = getOption("cores", default = getOption("Ncpus", default = parallel::detectCores())) |
| 8 | 65x | if (is.null(n_cores) || length(n_cores) == 0) { |
| 9 | ! | return(1L) |
| 10 | } | |
| 11 | 65x | n_cores = suppressWarnings(as.integer(n_cores[[1]])) |
| 12 | 65x | if (is.na(n_cores) || n_cores < 1L) { |
| 13 | 1x | return(1L) |
| 14 | } | |
| 15 | 64x | n_cores |
| 16 | } | |
| 17 | ||
| 18 | convert_ss_to_polygons = function(ss, progress = FALSE) { | |
| 19 | 65x | n_cores = get_n_cores() |
| 20 | 65x | list_all_polygons = convert_ss_to_polygons_rcpp(ss, n_cores, progress = progress) |
| 21 | 65x | return(list_all_polygons) |
| 22 | } |
| 1 | #' Generate a 3D roof model | |
| 2 | #' | |
| 3 | #' This function generates a 3D roof model from a straight skeleton. | |
| 4 | #' | |
| 5 | #' @param skeleton Default `NULL`. A straight skeleton generated from the `skeletonize` function. | |
| 6 | #' @param angle Default `45`. Angle of the roof. | |
| 7 | #' @param max_height Default `NA`. The maximum height of the roof. | |
| 8 | #' @param vertical_offset Default `0`. The vertical offset of the roof. | |
| 9 | #' @param base Default `TRUE`. A logical flag that controls whether to generate the bottom of the roof. | |
| 10 | #' @param base_height Default `vertical_offset`. Height of the base. | |
| 11 | #' @param sides Default `FALSE`. A logical flag on whether to draw the sides. This will automatically be set to `TRUE` | |
| 12 | #' if `base = TRUE` and the `base_height` is less than `vertical_offset`. | |
| 13 | #' @param double_sided Default `FALSE`. A logical flag that controls whether the polygon should be double-sided. | |
| 14 | #' @param swap_yz Default `TRUE`. A logical flag that controls whether to swap the y and z coordinates in the resulting mesh. | |
| 15 | #' If `TRUE`, the y and z coordinates will be swapped. | |
| 16 | #' @param progress Default `TRUE`. A logical flag to control whether a progress bar is displayed during roof generation. | |
| 17 | #' @param verbose Default `FALSE`. A logical flag to control whether additional timing information should be displayed. | |
| 18 | #' @param scale_all_max Default `FALSE`. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall | |
| 19 | #' max height, or whether to scale each max height to the maximum internal distance in the polygon. | |
| 20 | #' @param material Default `material_list()`. Interface to set the color/appearance/material options for the resulting `ray_mesh` mesh. | |
| 21 | #' @param roof_material Default `NA`, uses the material specified in `material`. Interface to set the color/appearance/material options for the resulting `ray_mesh` rooftop mesh. | |
| 22 | #' | |
| 23 | #' @return A 3D mesh of the roof model. | |
| 24 | #' | |
| 25 | #' @import rayvertex | |
| 26 | #' | |
| 27 | #' @export | |
| 28 | #' @examples | |
| 29 | #' #Generate vertices and holes | |
| 30 | #' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)-3.5 | |
| 31 | #' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]-3.5 | |
| 32 | #' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]-3.5 | |
| 33 | #' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2)) | |
| 34 | #' if(run_docs_raybevel()) { | |
| 35 | #' plot_skeleton(skeleton) | |
| 36 | #' } | |
| 37 | #' | |
| 38 | #' #Generate a roof model and specify the material | |
| 39 | #' if(run_docs_raybevel()) { | |
| 40 | #' library(rayrender) | |
| 41 | #' library(rayvertex) | |
| 42 | #' roof_model = generate_roof(skeleton, material = material_list(diffuse="purple")) | |
| 43 | #' scene_base = xz_rect(xwidth=100,zwidth=100, | |
| 44 | #' material=diffuse(color="grey20", checkercolor="white")) |> | |
| 45 | #' add_object(sphere(y=8,z=10,x=-3,material=light(intensity=100))) |> | |
| 46 | #' add_object(sphere(y=800,z=10,x=-3,radius=100,material=light(intensity=5))) | |
| 47 | #' | |
| 48 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 49 | #' add_object(scene_base) |> | |
| 50 | #' render_scene(lookfrom=c(10,30,20), samples=16, | |
| 51 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 52 | #' } | |
| 53 | #' | |
| 54 | #' # Change the maximum height of the roof | |
| 55 | #' if(run_docs_raybevel()) { | |
| 56 | #' roof_model = generate_roof(skeleton, max_height=5) | |
| 57 | #' raymesh_model(roof_model, material = diffuse(color="purple")) |> | |
| 58 | #' add_object(scene_base) |> | |
| 59 | #' render_scene(lookfrom=c(10,30,20), samples=16, | |
| 60 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 61 | #' } | |
| 62 | #' | |
| 63 | #' #Add a vertical_offset to the roof, without a base | |
| 64 | #' if(run_docs_raybevel()) { | |
| 65 | #' roof_model = generate_roof(skeleton, vertical_offset = 2, base = FALSE) | |
| 66 | #' raymesh_model(roof_model, material = diffuse(color="purple")) |> | |
| 67 | #' add_object(scene_base) |> | |
| 68 | #' render_scene(lookfrom=c(10,10,20), lookat=c(0,2,0), samples=16, | |
| 69 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 70 | #' } | |
| 71 | #' | |
| 72 | #' # Add a base | |
| 73 | #' if(run_docs_raybevel()) { | |
| 74 | #' roof_model = generate_roof(skeleton, vertical_offset = 2, base = TRUE) | |
| 75 | #' raymesh_model(roof_model, material = diffuse(color="purple")) |> | |
| 76 | #' add_object(scene_base) |> | |
| 77 | #' render_scene(lookfrom=c(10,10,20), lookat=c(0,2,0), samples=16, | |
| 78 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 79 | #' } | |
| 80 | #' | |
| 81 | #' # Change the base height (note that the vertical_offset is measured from the base, not from zero) | |
| 82 | #' if(run_docs_raybevel()) { | |
| 83 | #' roof_model = generate_roof(skeleton, vertical_offset = 2, base = TRUE, base_height=1) | |
| 84 | #' raymesh_model(roof_model, material = diffuse(color="purple")) |> | |
| 85 | #' add_object(scene_base) |> | |
| 86 | #' render_scene(lookfrom=c(10,10,20), lookat=c(0,2,0), samples=16, | |
| 87 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 88 | #' } | |
| 89 | #' | |
| 90 | #' | |
| 91 | #' # Skeletonize and turn an {sf} object into a roof | |
| 92 | #' if(run_docs_raybevel()) { | |
| 93 | #' us_states = spData::us_states | |
| 94 | #' cali = us_states[us_states$NAME == "California",] | |
| 95 | #' cali_skeleton = skeletonize(cali) | |
| 96 | #' plot_skeleton(cali_skeleton) | |
| 97 | #' roof_model_cali = generate_roof(cali_skeleton, max_height = 2) |> | |
| 98 | #' center_mesh() |> | |
| 99 | #' translate_mesh(c(0,1,0)) | |
| 100 | #' | |
| 101 | #' raymesh_model(roof_model_cali, material = diffuse(color="purple")) |> | |
| 102 | #' add_object(scene_base) |> | |
| 103 | #' add_object(sphere(x=-10,z=-10,y=4,material=light(color="red", intensity=40))) |> | |
| 104 | #' add_object(sphere(x=10,z=-10,y=4,material=light(color="orange", intensity=40))) |> | |
| 105 | #' render_scene(lookfrom=c(0,10,-1), samples=16, ambient_light=TRUE, | |
| 106 | #' width=800,height=800,fov=0, ortho_dimensions=c(12,12)) | |
| 107 | #' } | |
| 108 | generate_roof = function(skeleton, max_height = NA, vertical_offset = 0, | |
| 109 | base = FALSE, base_height = 0, angle = 45, | |
| 110 | sides = FALSE, double_sided = FALSE, scale_all_max = FALSE, | |
| 111 | swap_yz = TRUE, progress = TRUE, | |
| 112 | material = material_list(), | |
| 113 | roof_material = NA, | |
| 114 | verbose = FALSE) { | |
| 115 | 1x | if(run_docs_raybevel() || !interactive()) { |
| 116 | 1x | progress = FALSE |
| 117 | } | |
| 118 | 1x | if(!is.list(roof_material)) { |
| 119 | ! | roof_material = material |
| 120 | } | |
| 121 | 1x | if(inherits(skeleton, "rayskeleton_list")) { |
| 122 | ! | pb = progress::progress_bar$new( |
| 123 | ! | format = ":current/:total Generating roof [:bar] eta: :eta", |
| 124 | ! | total = length(skeleton), clear = TRUE, width = 60) |
| 125 | ! | meshlist = list() |
| 126 | ! | counter = 1 |
| 127 | ! | vec_default = function(length_skeleton, value) { |
| 128 | ! | if(length(value) == 1) { |
| 129 | ! | return(rep(value,length(skeleton))) |
| 130 | } else { | |
| 131 | ! | stopifnot(length(value) == length_skeleton) |
| 132 | ! | return(value) |
| 133 | } | |
| 134 | } | |
| 135 | ! | len_s = length(skeleton) |
| 136 | ! | vertical_offset = vec_default(len_s, vertical_offset) |
| 137 | ! | base_height = vec_default(len_s, base_height) |
| 138 | ! | angle = vec_default(len_s, angle) |
| 139 | ! | if(!is.na(max_height)) { |
| 140 | ! | if(length(max_height) == 1) { |
| 141 | ! | if(scale_all_max) { |
| 142 | ! | max_height = rep(max_height,length(skeleton)) |
| 143 | } else { | |
| 144 | #Calculate proportional maximum heights | |
| 145 | ! | single_max_heights = unlist(lapply(skeleton, \(x) max(x$nodes$time))) |
| 146 | ! | max_height = single_max_heights/max(single_max_heights) * max_height |
| 147 | } | |
| 148 | } else { | |
| 149 | ! | stopifnot(length(max_height) == length(skeleton)) |
| 150 | } | |
| 151 | } | |
| 152 | ! | for(j in seq_len(length(skeleton))) { |
| 153 | ! | if(progress) { |
| 154 | ! | pb$tick() |
| 155 | } | |
| 156 | ! | meshlist[[counter]] = generate_roof(skeleton[[j]], |
| 157 | ! | base = base, |
| 158 | ! | max_height = max_height[j], |
| 159 | ! | sides = sides, |
| 160 | ! | double_sided = double_sided, |
| 161 | ! | base_height = base_height[j], |
| 162 | ! | vertical_offset = vertical_offset[j], |
| 163 | ! | angle = angle[j], |
| 164 | ! | swap_yz = swap_yz, |
| 165 | ! | material = material, |
| 166 | ! | roof_material = roof_material, |
| 167 | ! | progress = FALSE) |
| 168 | ! | counter = counter + 1 |
| 169 | } | |
| 170 | ! | return(scene_from_list(meshlist)) |
| 171 | } | |
| 172 | 1x | if(!inherits(skeleton, "rayskeleton")) { |
| 173 | ! | stop("`skeleton` must be of class `rayskeleton`") |
| 174 | } | |
| 175 | 1x | angle_slope = tanpi(angle/180) |
| 176 | 1x | if(is.na(max_height)) { |
| 177 | ! | max_height = max(skeleton$nodes$time) * angle_slope |
| 178 | } | |
| 179 | ||
| 180 | 1x | polygon_ind = convert_ss_to_polygons(skeleton, progress = progress) |
| 181 | 1x | nodes = skeleton$nodes |
| 182 | 1x | index_list = list() |
| 183 | 1x | for(i in seq_len(length(polygon_ind))) { |
| 184 | 4x | tmp_ind = polygon_ind[[i]] |
| 185 | 4x | tmp_poly = nodes[tmp_ind,2:3] |
| 186 | 4x | index_list[[i]] = matrix(tmp_ind[decido::earcut(tmp_poly)],byrow=TRUE,ncol=3) |
| 187 | } | |
| 188 | 1x | indices_all = do.call("rbind",index_list) |
| 189 | 1x | xyz = nodes[,2:4] |
| 190 | 1x | colnames(xyz) = c("x","y","z") |
| 191 | 1x | if(!is.na(max_height)) { |
| 192 | 1x | stopifnot(max_height >= 0) |
| 193 | 1x | xyz[,3] = xyz[,3]/max(xyz[,3]) * max_height |
| 194 | } | |
| 195 | 1x | original_verts = attr(skeleton,"original_vertices") |
| 196 | 1x | original_holes = attr(skeleton,"original_holes") |
| 197 | 1x | side_top = vertical_offset |
| 198 | ||
| 199 | 1x | mesh = construct_mesh(vertices = as.matrix(xyz), |
| 200 | 1x | indices = as.matrix(indices_all)-1) |> |
| 201 | 1x | translate_mesh(c(0,0,vertical_offset)) |> |
| 202 | 1x | set_material(roof_material) |
| 203 | ||
| 204 | 1x | if(double_sided) { |
| 205 | ! | xyzflip = xyz |
| 206 | ! | xyzflip[,3] = -xyzflip[,3] |
| 207 | ! | indices_flip = indices_all[,3:1,drop=FALSE] |
| 208 | ! | double_mesh = construct_mesh(vertices = as.matrix(xyzflip), |
| 209 | ! | indices = as.matrix(indices_flip)-1) |> |
| 210 | ! | set_material(roof_material) |
| 211 | } | |
| 212 | 1x | if(base && !double_sided) { |
| 213 | 1x | if(length(original_holes) > 0) { |
| 214 | ! | holes = c(0,utils::head(cumsum(unlist(lapply(original_holes,nrow))),-1)) + nrow(original_verts) + 1 |
| 215 | ! | hole_mat = do.call("rbind", original_holes) |
| 216 | ! | original_verts_holes = rbind(original_verts, hole_mat) |
| 217 | } else { | |
| 218 | 1x | holes = 0 |
| 219 | 1x | original_verts_holes = original_verts |
| 220 | } | |
| 221 | 1x | base_indices = matrix(decido::earcut(original_verts_holes, holes = holes), byrow = TRUE, ncol=3) |
| 222 | 1x | base_indices = base_indices[,3:1,drop = FALSE] |
| 223 | 1x | original_verts_base = cbind(original_verts_holes, rep(0, nrow(original_verts_holes))) |
| 224 | 1x | base_mesh = construct_mesh(vertices = as.matrix(original_verts_base), |
| 225 | 1x | indices = as.matrix(base_indices)-1) |> |
| 226 | 1x | set_material(material) |
| 227 | ||
| 228 | 1x | mesh = mesh |> |
| 229 | 1x | add_shape(base_mesh) |
| 230 | } | |
| 231 | 1x | if(double_sided) { |
| 232 | ! | mesh = add_shape(mesh, double_mesh) |
| 233 | } | |
| 234 | 1x | if((sides || base || double_sided) && |
| 235 | 1x | ((!double_sided && side_top > 0) || (double_sided && side_top > 0))) { |
| 236 | 1x | if(!double_sided) { |
| 237 | 1x | side_mesh = extrude_sides(original_verts, original_holes, bottom = 0, top = side_top) |
| 238 | } else { | |
| 239 | ! | side_mesh = extrude_sides(original_verts, original_holes, bottom = -side_top, top = side_top) |
| 240 | } | |
| 241 | 1x | side_mesh = side_mesh |> |
| 242 | 1x | set_material(material) |
| 243 | 1x | mesh = add_shape(mesh, side_mesh) |
| 244 | } | |
| 245 | 1x | if(!is.na(base_height)) { |
| 246 | 1x | mesh = translate_mesh(mesh, c(0,0,base_height)) |
| 247 | } | |
| 248 | 1x | if(swap_yz) { |
| 249 | 1x | mesh = swap_yz(mesh) |
| 250 | } | |
| 251 | 1x | print_time(verbose, "Generated mesh") |
| 252 | 1x | return(mesh) |
| 253 | } | |
| 254 | ||
| 255 | #' Generate a beveled 3D polygon | |
| 256 | #' | |
| 257 | #' This function generates a beveled 3D polygon from a straight skeleton. | |
| 258 | #' | |
| 259 | #' @param skeleton Default `NULL`. A straight skeleton generated from the `skeletonize` function. | |
| 260 | #' @param bevel_offsets Default `NULL`. The offset(s) of the bevel. | |
| 261 | #' @param max_height Default `1`. The maximum height of the polygon. | |
| 262 | #' @param bevel_heights Default is set to `bevel_offsets`. Numeric vector specifying the heights of the bevels. Must be of the same length as `bevel_offsets`. | |
| 263 | #' @param set_max_height Default `FALSE`. A logical flag that controls whether to set the max height of the roof based on the `max_height` argument. | |
| 264 | #' @param swap_yz Default `TRUE`. A logical flag that controls whether to swap the y and z coordinates in the resulting mesh. If `TRUE`, the y and z coordinates will be swapped. | |
| 265 | #' @param progress Default `TRUE`. A logical flag to control whether a progress bar is displayed during roof generation. | |
| 266 | #' @param vertical_offset Default `0`. The vertical offset of the polygon. | |
| 267 | #' @param base Default `TRUE`. A logical flag that controls whether to generate the bottom of the polygon. | |
| 268 | #' @param base_height Default `NA`. Height of the base, defaulting to `min(bevel_heights) + vertical_offset` . | |
| 269 | #' @param sides Default `FALSE`. A logical flag on whether to draw the sides. This will automatically be set to `TRUE` | |
| 270 | #' if `base = TRUE` and the `base_height` is less than `vertical_offset`. | |
| 271 | #' @param scale_all_max Default `FALSE`. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall | |
| 272 | #' max height, or whether to scale each max height to the maximum internal distance in the polygon. | |
| 273 | #' @param verbose Default `FALSE`. A logical flag to control whether additional timing information should be displayed. | |
| 274 | #' @param raw_offsets Default `FALSE`. A logical flag indicating whether the `bevel_offsets` are already in raw format and do not need to be multiplied by the maximum time of the skeleton. | |
| 275 | #' @param raw_heights Default `FALSE`. A logical flag indicating whether the `bevel_heights` are already in raw format and do not need to be multiplied by the maximum time of the skeleton. | |
| 276 | #' @param double_sided Default `FALSE`. A logical flag that controls whether the polygon should be double-sided. | |
| 277 | #' @param return_skeleton_polygons Default `FALSE`. A logical flag that controls whether to return the skeleton polygons along with the 3D mesh. | |
| 278 | #' @param material Default `material_list()`. Interface to set the color/appearance/material options for the resulting `ray_mesh` mesh. | |
| 279 | #' @param bevel_material Default `NA`, uses the material specified in `material`. Interface to set the color/appearance/material options for the resulting `ray_mesh` bevel mesh. | |
| 280 | #' | |
| 281 | #' @return A 3D mesh of the beveled polygon model. | |
| 282 | #' | |
| 283 | #' @import rayvertex | |
| 284 | #' | |
| 285 | #' @export | |
| 286 | #' @examples | |
| 287 | #' #Generate vertices and holes | |
| 288 | #' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)-3.5 | |
| 289 | #' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]-3.5 | |
| 290 | #' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]-3.5 | |
| 291 | #' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2)) | |
| 292 | #' if(run_docs_raybevel()) { | |
| 293 | #' plot_skeleton(skeleton) | |
| 294 | #' } | |
| 295 | #' | |
| 296 | #' #Generate a roof model and specify the material | |
| 297 | #' if(run_docs_raybevel()) { | |
| 298 | #' library(rayrender) | |
| 299 | #' library(rayvertex) | |
| 300 | #' | |
| 301 | #' scene_base = xz_rect(xwidth=100,zwidth=100, | |
| 302 | #' material=diffuse(color="grey20", checkercolor="white")) |> | |
| 303 | #' add_object(sphere(y=8,z=10,x=-3,material=light(intensity=100))) |> | |
| 304 | #' add_object(sphere(y=800,z=10,x=-3,radius=100,material=light(intensity=5))) |> | |
| 305 | #' add_object(sphere(x=-10,z=-10,y=5,material=light(color="red", intensity=40))) |> | |
| 306 | #' add_object(sphere(x=10,z=-10,y=5,material=light(color="orange", intensity=40))) | |
| 307 | #' | |
| 308 | #' bevel = generate_bevel("angled", bevel_start = 0, bevel_end = 0.2, max_height=0.25) | |
| 309 | #' roof_model = generate_beveled_polygon(skeleton, | |
| 310 | #' bevel_offsets = bevel, | |
| 311 | #' material = material_list(diffuse="purple")) | |
| 312 | #' #Visualize with rayvertex | |
| 313 | #' roof_model |> | |
| 314 | #' add_shape(xz_rect_mesh(scale=c(20,1,20)) ) |> | |
| 315 | #' rasterize_scene(lookfrom=c(10,10,10),fov=40, | |
| 316 | #' light_info = directional_light(c(-0.5,0.7,0.8))) | |
| 317 | #' | |
| 318 | #' #Visualize with rayrender | |
| 319 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 320 | #' add_object(scene_base) |> | |
| 321 | #' render_scene(lookfrom=c(10,30,20),samples=16, | |
| 322 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10), verbose=TRUE) | |
| 323 | #' } | |
| 324 | #' | |
| 325 | #' # Change the bevel to be circular | |
| 326 | #' if(run_docs_raybevel()) { | |
| 327 | #' bevel = generate_bevel("circular", bevel_start = 0, bevel_end = 0.2, max_height=0.25) | |
| 328 | #' roof_model = generate_beveled_polygon(skeleton, | |
| 329 | #' bevel_offsets = bevel, | |
| 330 | #' material = material_list(diffuse="purple")) | |
| 331 | #' | |
| 332 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 333 | #' add_object(scene_base) |> | |
| 334 | #' render_scene(lookfrom=c(10,30,20), samples=16, | |
| 335 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 336 | #' } | |
| 337 | #' | |
| 338 | #' # Change the bevel to type "bump", change the max height, and raise it off the surface | |
| 339 | #' if(run_docs_raybevel()) { | |
| 340 | #' bevel = generate_bevel("bump", bevel_start = 0, bevel_end = 0.4, max_height=0.25) | |
| 341 | #' roof_model = generate_beveled_polygon(skeleton, base_height=1, | |
| 342 | #' bevel_offsets = bevel, | |
| 343 | #' material = material_list(diffuse="purple")) | |
| 344 | #' | |
| 345 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 346 | #' add_object(scene_base) |> | |
| 347 | #' render_scene(lookfrom=c(10,30,20), samples=16, | |
| 348 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 349 | #' } | |
| 350 | #' | |
| 351 | #' # Generate a complex bevel and use the exact specified heights | |
| 352 | #' if(run_docs_raybevel()) { | |
| 353 | #' bevel = generate_complex_bevel(c("bump", "exp", "circular","step"), | |
| 354 | #' bevel_start = c(0,0.3,0.7,0.95), | |
| 355 | #' bevel_end = c(0.1,0.6,0.95,1), | |
| 356 | #' reverse = c(F,F,T,F), | |
| 357 | #' segment_height = c(0.25,0.5,0.5,4), | |
| 358 | #' plot_bevel = TRUE) | |
| 359 | #' | |
| 360 | #' roof_model = generate_beveled_polygon(skeleton, vertical_offset=0.1, | |
| 361 | #' bevel_offsets = bevel, | |
| 362 | #' raw_heights = TRUE, | |
| 363 | #' material = material_list(diffuse="purple")) | |
| 364 | #' | |
| 365 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 366 | #' add_object(scene_base) |> | |
| 367 | #' render_scene(lookfrom=c(10,30,20), samples=16, | |
| 368 | #' width=800,height=800,fov=0,ortho_dimensions=c(10,10)) | |
| 369 | #' } | |
| 370 | #' | |
| 371 | #' # Turn the polygon into a ziggurat, using the step bevel type | |
| 372 | #' if(run_docs_raybevel()) { | |
| 373 | #' offs = seq(0, 1, by = 0.05) | |
| 374 | #' bevel = generate_complex_bevel("step", | |
| 375 | #' bevel_start = offs[-length(offs)], | |
| 376 | #' bevel_end = offs[-1], | |
| 377 | #' segment_height = 0.2) | |
| 378 | #' | |
| 379 | #' roof_model = generate_beveled_polygon(skeleton, vertical_offset=0.2, | |
| 380 | #' bevel_offsets = bevel, | |
| 381 | #' raw_heights = TRUE, | |
| 382 | #' material = material_list(diffuse = "purple")) | |
| 383 | #' | |
| 384 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 385 | #' add_object(scene_base) |> | |
| 386 | #' render_scene(lookfrom = c(10,30,20), samples=16, | |
| 387 | #' width = 800, height = 800, fov = 0, ortho_dimensions = c(10,10)) | |
| 388 | #' } | |
| 389 | #' | |
| 390 | #' # Turn the polygon into a smooth wavy slide, taking advantage of vector recycling to flip/reverse | |
| 391 | #' if(run_docs_raybevel()) { | |
| 392 | #' offs = seq(0, 1, by = 0.1) | |
| 393 | #' bevel = generate_complex_bevel("exp", | |
| 394 | #' bevel_start = offs[-length(offs)], | |
| 395 | #' bevel_end = offs[-1], | |
| 396 | #' reverse = c(TRUE, FALSE), | |
| 397 | #' flip = c(TRUE, FALSE), | |
| 398 | #' segment_height = 0.25) | |
| 399 | #' | |
| 400 | #' roof_model = generate_beveled_polygon(skeleton, vertical_offset=0.2, | |
| 401 | #' bevel_offsets = bevel, | |
| 402 | #' raw_heights = TRUE, | |
| 403 | #' material = material_list(diffuse = "purple")) | |
| 404 | #' | |
| 405 | #' raymesh_model(roof_model, override_material = FALSE) |> | |
| 406 | #' add_object(scene_base) |> | |
| 407 | #' render_scene(lookfrom = c(10,30,20), samples=16, | |
| 408 | #' width = 800, height = 800, fov = 0, ortho_dimensions = c(10,10)) | |
| 409 | #' } | |
| 410 | #' | |
| 411 | #' # Skeletonize and turn an {sf} object into a beveled polygon | |
| 412 | #' if(run_docs_raybevel()) { | |
| 413 | #' us_states = spData::us_states | |
| 414 | #' texas = us_states[us_states$NAME == "Texas",] | |
| 415 | #' texas_skeleton = skeletonize(texas) | |
| 416 | #' plot_skeleton(texas_skeleton) | |
| 417 | #' | |
| 418 | #' bevel = generate_bevel("angled" , bevel_end=0.3, max_height = 0.3) | |
| 419 | #' roof_model_texas = generate_beveled_polygon(texas_skeleton, | |
| 420 | #' bevel_offsets = bevel, | |
| 421 | #' material = material_list(diffuse = "purple")) |> | |
| 422 | #' center_mesh() |> | |
| 423 | #' translate_mesh(c(0,0.3,0)) | |
| 424 | #' | |
| 425 | #' raymesh_model(roof_model_texas, material = diffuse(color="purple")) |> | |
| 426 | #' add_object(scene_base) |> | |
| 427 | #' add_object(sphere(x=-10,z=-10,y=5,material=light(color="red", intensity=40))) |> | |
| 428 | #' add_object(sphere(x=10,z=-10,y=5,material=light(color="orange", intensity=40))) |> | |
| 429 | #' render_scene(lookfrom=c(0,10,0),camera_up=c(0,0,1), samples=16, | |
| 430 | #' width=800,height=800,fov=0, ortho_dimensions=c(15,15)) | |
| 431 | #' } | |
| 432 | #' | |
| 433 | #' # Generate a smooth bevel | |
| 434 | #' if(run_docs_raybevel()) { | |
| 435 | #' bevel = generate_bevel("exp", bevel_start = 0, bevel_end=0.5, max_height=2) | |
| 436 | #' roof_model_texas = generate_beveled_polygon(texas_skeleton, | |
| 437 | #' bevel_offsets = bevel, | |
| 438 | #' material = material_list(diffuse = "purple")) |> | |
| 439 | #' center_mesh() |> | |
| 440 | #' translate_mesh(c(0,0.5,0)) | |
| 441 | #' | |
| 442 | #' raymesh_model(roof_model_texas, material = diffuse(color="purple")) |> | |
| 443 | #' add_object(scene_base) |> | |
| 444 | #' add_object(sphere(x=-10,z=-10,y=5,material=light(color="red", intensity=40))) |> | |
| 445 | #' add_object(sphere(x=10,z=-10,y=5,material=light(color="orange", intensity=40))) |> | |
| 446 | #' render_scene(lookfrom=c(0,10,0),camera_up=c(0,0,1), samples=16, | |
| 447 | #' width=800,height=800,fov=0, ortho_dimensions=c(15,15)) | |
| 448 | #' } | |
| 449 | generate_beveled_polygon = function(skeleton, | |
| 450 | bevel_offsets = generate_bevel(), | |
| 451 | bevel_heights = NULL, | |
| 452 | set_max_height = FALSE, | |
| 453 | max_height = NA, | |
| 454 | vertical_offset = 0, | |
| 455 | base = TRUE, | |
| 456 | base_height = 0, | |
| 457 | raw_offsets = FALSE, | |
| 458 | raw_heights = FALSE, | |
| 459 | swap_yz = TRUE, | |
| 460 | progress = TRUE, | |
| 461 | double_sided = FALSE, | |
| 462 | sides = FALSE, | |
| 463 | return_skeleton_polygons = FALSE, | |
| 464 | scale_all_max = FALSE, | |
| 465 | material = material_list(), | |
| 466 | bevel_material = NA, | |
| 467 | verbose = FALSE) { | |
| 468 | 320x | if(run_docs_raybevel() || !interactive()) { |
| 469 | 320x | progress = FALSE |
| 470 | } | |
| 471 | 320x | if(!is.list(bevel_material)) { |
| 472 | 320x | bevel_material = material |
| 473 | } | |
| 474 | 320x | init_time() |
| 475 | 320x | if(inherits(skeleton, "rayskeleton_list")) { |
| 476 | ! | pb = progress::progress_bar$new( |
| 477 | ! | format = ":current/:total Generating bevel [:bar] eta: :eta", |
| 478 | ! | total = length(skeleton), clear = TRUE, width = 60) |
| 479 | ! | meshlist = list() |
| 480 | ! | counter = 1 |
| 481 | ! | vec_default = function(length_skeleton, value) { |
| 482 | ! | if(length(value) == 1) { |
| 483 | ! | return(rep(value,length(skeleton))) |
| 484 | } else { | |
| 485 | ! | stopifnot(length(value) == length_skeleton) |
| 486 | ! | return(value) |
| 487 | } | |
| 488 | } | |
| 489 | ! | len_s = length(skeleton) |
| 490 | ! | vertical_offset = vec_default(len_s, vertical_offset) |
| 491 | ! | base_height = vec_default(len_s, base_height) |
| 492 | ! | if(length(max_height) == 1) { |
| 493 | ! | if(scale_all_max) { |
| 494 | ! | max_height = rep(max_height,length(skeleton)) |
| 495 | } else { | |
| 496 | #Calculate proportional maximum heights | |
| 497 | ! | single_max_heights = unlist(lapply(skeleton, \(x) max(x$nodes$time))) |
| 498 | ! | max_height = single_max_heights/max(single_max_heights) * max_height |
| 499 | } | |
| 500 | } | |
| 501 | ! | for(j in seq_len(length(skeleton))) { |
| 502 | ! | if(progress) { |
| 503 | ! | pb$tick() |
| 504 | } | |
| 505 | ! | meshlist[[counter]] = generate_beveled_polygon(skeleton[[j]], |
| 506 | ! | bevel_offsets = bevel_offsets, |
| 507 | ! | bevel_heights = bevel_heights, |
| 508 | ! | bevel_material = bevel_material, |
| 509 | ! | base = base, |
| 510 | ! | vertical_offset = vertical_offset[j], |
| 511 | ! | max_height = max_height[j], |
| 512 | ! | raw_offsets = raw_offsets, |
| 513 | ! | raw_heights = raw_heights, |
| 514 | ! | sides = sides, |
| 515 | ! | double_sided = double_sided, |
| 516 | ! | base_height = base_height[j], |
| 517 | ! | set_max_height = set_max_height, |
| 518 | ! | return_skeleton_polygons = return_skeleton_polygons, |
| 519 | ! | swap_yz = swap_yz, |
| 520 | ! | progress = progress, |
| 521 | ! | material = material) |
| 522 | ! | counter = counter + 1 |
| 523 | } | |
| 524 | ! | if(return_skeleton_polygons) { |
| 525 | ! | class(meshlist) = c("rayskeleton_list_polygons", "list") |
| 526 | ! | return(meshlist) |
| 527 | } | |
| 528 | ! | return(scene_from_list(meshlist)) |
| 529 | } | |
| 530 | 320x | if(!inherits(skeleton, "rayskeleton")) { |
| 531 | ! | stop("`skeleton` must be of class `rayskeleton`") |
| 532 | } | |
| 533 | 320x | max_time = max(skeleton$links$destination_time) |
| 534 | 320x | if(is.list(bevel_offsets) && |
| 535 | 320x | !is.null(bevel_offsets$x) && |
| 536 | 320x | !is.null(bevel_offsets$y)) { |
| 537 | ! | bevel_heights = bevel_offsets$y |
| 538 | ! | bevel_offsets = bevel_offsets$x |
| 539 | } | |
| 540 | ||
| 541 | 320x | if(!raw_offsets) { |
| 542 | ! | if(any(bevel_offsets > 1 | bevel_offsets < 0)) { |
| 543 | ! | stop("If using percentage offsets, all `bevel_offsets` must be between 0 and 1.") |
| 544 | } | |
| 545 | ! | bevel_offsets = bevel_offsets * max_time |
| 546 | } | |
| 547 | 320x | non_zero_offsets = bevel_offsets[bevel_offsets > 0] |
| 548 | 320x | if(all(non_zero_offsets >= max_time)) { |
| 549 | ! | message(sprintf("All `bevel_offset` greater than max offset in polygon of %f, calculating full polygon model", |
| 550 | ! | max(skeleton$nodes[,4]))) |
| 551 | ! | interpolated_data = stats::approx(x = c(bevel_offsets), |
| 552 | ! | y = c(bevel_heights), |
| 553 | ! | xout = max_time) |
| 554 | ! | max_height = max(interpolated_data$y) |
| 555 | ! | return(generate_roof(skeleton, |
| 556 | ! | max_height = max_height, |
| 557 | ! | base_height = base_height, |
| 558 | ! | vertical_offset = vertical_offset, |
| 559 | ! | swap_yz = swap_yz, |
| 560 | ! | base = base, |
| 561 | ! | sides = sides, |
| 562 | ! | double_sided = double_sided, |
| 563 | ! | progress = progress, |
| 564 | ! | roof_material = bevel_material, |
| 565 | ! | material = material)) |
| 566 | } | |
| 567 | 320x | if(!raw_heights) { |
| 568 | ! | bevel_heights = bevel_heights * max_time |
| 569 | } | |
| 570 | ||
| 571 | 320x | bevel_heights = bevel_heights[order(bevel_offsets)] |
| 572 | 320x | bevel_offsets = bevel_offsets[order(bevel_offsets)] |
| 573 | ||
| 574 | 320x | height_range = range(bevel_heights) |
| 575 | 320x | height_range = height_range[2]-height_range[1] |
| 576 | 320x | if(set_max_height && !is.na(max_height)) { |
| 577 | 160x | stopifnot(max_height > 0) |
| 578 | 160x | min_height = min(bevel_heights) |
| 579 | 160x | offset_bevel_heights = bevel_heights - min_height |
| 580 | 160x | offset_bevel_heights = max_height * offset_bevel_heights / height_range + min_height |
| 581 | 160x | height_range = max_height |
| 582 | 160x | bevel_heights = offset_bevel_heights |
| 583 | } | |
| 584 | 320x | stopifnot(length(vertical_offset) == 1) |
| 585 | 320x | stopifnot(vertical_offset >= 0) |
| 586 | 64x | bevel_heights = bevel_heights + vertical_offset |
| 587 | ||
| 588 | 64x | valid_bevels = bevel_offsets <= max_time & bevel_offsets > 0 |
| 589 | 64x | zero_height_val = bevel_heights[1] |
| 590 | 64x | bevel_offsets_polys = bevel_offsets[valid_bevels] |
| 591 | 64x | bevel_heights_polys = bevel_heights[valid_bevels] |
| 592 | ||
| 593 | 64x | stopifnot(length(bevel_offsets_polys) == length(bevel_heights_polys)) |
| 594 | ||
| 595 | #Remove extremely close offsets (usually arising from floating point error) | |
| 596 | 64x | for(i in rev(seq_len(length(bevel_offsets_polys)))) { |
| 597 | 320x | all_other_offsets = bevel_offsets_polys[-i] |
| 598 | 320x | if(any(abs(bevel_offsets_polys[i] - all_other_offsets) < 1e-14, na.rm = TRUE)) { |
| 599 | ! | bevel_offsets_polys[i] = NA |
| 600 | } | |
| 601 | } | |
| 602 | 64x | remove_close_vals = !is.na(bevel_offsets_polys) |
| 603 | 64x | bevel_offsets_polys = bevel_offsets_polys[remove_close_vals] |
| 604 | 64x | bevel_heights_polys = bevel_heights_polys[remove_close_vals] |
| 605 | ||
| 606 | #Generate new nodes | |
| 607 | 64x | beveled_ss = generate_offset_links_nodes(skeleton, bevel_offsets_polys, verbose = verbose, progress = progress) |
| 608 | 64x | print_time(verbose, "Generated offset links") |
| 609 | ||
| 610 | 64x | reordered_new_ss = recalculate_ordered_ids(beveled_ss) |
| 611 | 64x | print_time(verbose, "Recalculated ordered IDs") |
| 612 | ||
| 613 | 64x | polygon_ind = convert_ss_to_polygons(reordered_new_ss, progress = progress) |
| 614 | 64x | print_time(verbose, "Converted to polygons") |
| 615 | ||
| 616 | 64x | nodes = reordered_new_ss$nodes |
| 617 | 64x | index_list = list() |
| 618 | 64x | for(i in seq_len(length(polygon_ind))) { |
| 619 | 3584x | tmp_ind = polygon_ind[[i]] |
| 620 | 3584x | tmp_poly = nodes[tmp_ind,2:3] |
| 621 | 3584x | index_list[[i]] = matrix(tmp_ind[decido::earcut(tmp_poly)],byrow=TRUE,ncol=3) |
| 622 | } | |
| 623 | 64x | print_time(verbose, "Triangulated polygons") |
| 624 | ||
| 625 | 64x | if(length(index_list) == 1) { |
| 626 | ! | indices_all = matrix(unlist(index_list),ncol=3, byrow = TRUE) |
| 627 | } else { | |
| 628 | 64x | indices_all = do.call("rbind",index_list) |
| 629 | } | |
| 630 | 64x | xyz = nodes[,2:4] |
| 631 | 64x | new_xyz = xyz |
| 632 | 64x | bevel_offsets_polys = c(0,bevel_offsets_polys) |
| 633 | 64x | bevel_heights_polys = c(zero_height_val,bevel_heights_polys) |
| 634 | ||
| 635 | 64x | if(bevel_offsets_polys[length(bevel_offsets_polys)] != max_time) { |
| 636 | 64x | bevel_offsets_with_max = c(bevel_offsets_polys, max_time) |
| 637 | 64x | bevel_heights_with_max = c(bevel_heights_polys, max(bevel_heights_polys)) |
| 638 | } else { | |
| 639 | ! | bevel_offsets_with_max = bevel_offsets_polys |
| 640 | ! | bevel_heights_with_max = bevel_heights_polys |
| 641 | } | |
| 642 | 64x | side_top = bevel_heights_with_max[1] |
| 643 | ||
| 644 | 64x | if(return_skeleton_polygons) { |
| 645 | ! | attr(reordered_new_ss, "polygons") = polygon_ind |
| 646 | #These offsets should always be normalized | |
| 647 | ! | attr(reordered_new_ss, "bevel_offsets") = bevel_offsets_with_max / max_time |
| 648 | ! | attr(reordered_new_ss, "raw_offsets") = raw_offsets |
| 649 | ! | class(reordered_new_ss) = c("rayskeleton_polygon") |
| 650 | ! | return(reordered_new_ss) |
| 651 | } | |
| 652 | #Need to account for non-zero offsets--not all start at 0 | |
| 653 | 64x | new_xyz[,3] = stats::approx(x=bevel_offsets_with_max,y=bevel_heights_with_max, xout = xyz[,3], rule=2)$y |
| 654 | ||
| 655 | 64x | xyz = new_xyz |
| 656 | 64x | colnames(xyz) = c("x","y","z") |
| 657 | 64x | original_verts = attr(skeleton,"original_vertices") |
| 658 | 64x | original_holes = attr(skeleton,"original_holes") |
| 659 | 64x | mesh = construct_mesh(vertices = as.matrix(xyz), |
| 660 | 64x | indices = as.matrix(indices_all)-1) |> |
| 661 | 64x | set_material(bevel_material) |
| 662 | ||
| 663 | 64x | if(double_sided) { |
| 664 | 32x | xyzflip = xyz |
| 665 | 32x | xyzflip[,3] = -xyzflip[,3] |
| 666 | 32x | indices_flip = indices_all[,3:1,drop=FALSE] |
| 667 | 32x | double_mesh = construct_mesh(vertices = as.matrix(xyzflip), |
| 668 | 32x | indices = as.matrix(indices_flip)-1) |> |
| 669 | 32x | set_material(bevel_material) |
| 670 | } | |
| 671 | 64x | if(base && !double_sided) { |
| 672 | 16x | if(length(original_holes) > 0) { |
| 673 | 16x | holes = c(0,utils::head(cumsum(unlist(lapply(original_holes,nrow))),-1)) + nrow(original_verts) + 1 |
| 674 | 16x | hole_mat = do.call("rbind", original_holes) |
| 675 | 16x | original_verts_holes = rbind(original_verts, hole_mat) |
| 676 | } else { | |
| 677 | ! | holes = 0 |
| 678 | ! | original_verts_holes = original_verts |
| 679 | } | |
| 680 | 16x | base_indices = matrix(decido::earcut(original_verts_holes, holes = holes), byrow = TRUE, ncol=3) |
| 681 | 16x | base_indices = base_indices[,3:1,drop = FALSE] |
| 682 | 16x | original_verts_base = cbind(original_verts_holes, rep(0, nrow(original_verts_holes))) |
| 683 | 16x | base_mesh = construct_mesh(vertices = as.matrix(original_verts_base), |
| 684 | 16x | indices = as.matrix(base_indices)-1) |> |
| 685 | 16x | set_material(material) |
| 686 | ||
| 687 | 16x | mesh = mesh |> |
| 688 | 16x | add_shape(base_mesh) |
| 689 | } | |
| 690 | 64x | if(double_sided) { |
| 691 | 32x | mesh = add_shape(mesh, double_mesh) |
| 692 | } | |
| 693 | 64x | if((sides || base || double_sided) && |
| 694 | 64x | ((!double_sided && side_top > 0) || (double_sided && side_top > 0))) { |
| 695 | 56x | if(!double_sided) { |
| 696 | 24x | side_mesh = extrude_sides(original_verts, original_holes, bottom = 0, top = side_top) |
| 697 | } else { | |
| 698 | 32x | side_mesh = extrude_sides(original_verts, original_holes, bottom = -side_top, top = side_top) |
| 699 | } | |
| 700 | 56x | side_mesh = side_mesh |> |
| 701 | 56x | set_material(material) |
| 702 | 56x | mesh = add_shape(mesh, side_mesh) |
| 703 | } | |
| 704 | 64x | if(swap_yz) { |
| 705 | 64x | mesh = swap_yz(mesh) |
| 706 | } | |
| 707 | 64x | if(!is.na(base_height)) { |
| 708 | 48x | if(swap_yz) { |
| 709 | 48x | mesh = translate_mesh(mesh, c(0,base_height,0)) |
| 710 | } else { | |
| 711 | ! | mesh = translate_mesh(mesh, c(0,0,base_height)) |
| 712 | } | |
| 713 | } | |
| 714 | 64x | print_time(verbose, "Generated mesh") |
| 715 | ||
| 716 | 64x | return(mesh) |
| 717 | } | |
| 718 | ||
| 719 | #' Change an existing polygon bevel's bevel profile. | |
| 720 | #' | |
| 721 | #' This function generates a beveled 3D polygon model from the modified straight skeleton with | |
| 722 | #' pre-existing polygons generated from the `generate_beveled_polygon` function when | |
| 723 | #' `return_skeleton_polygons = TRUE`. | |
| 724 | #' | |
| 725 | #' @param skeleton_polygons Default `NULL`. A straight skeleton generated from the `generate_beveled_polygon` function when | |
| 726 | #' `return_skeleton_polygons = TRUE`. | |
| 727 | #' @param bevel_offsets Default `NULL`. The offset(s) of the bevel. | |
| 728 | #' @param bevel_heights Default is set to `bevel_offsets`. Numeric vector specifying the heights of the bevels. Must be of the same length as `bevel_offsets`. | |
| 729 | #' @param max_height Default `1`. The maximum height of the polygon. | |
| 730 | #' @param set_max_height Default `FALSE`. A logical flag that controls whether to set the max height of the polygon based on the `max_height` argument. | |
| 731 | #' @param swap_yz Default `TRUE`. A logical flag that controls whether to swap the y and z coordinates in the resulting mesh. | |
| 732 | #' If `TRUE`, the y and z coordinates will be swapped. | |
| 733 | #' @param sides Default `FALSE`. A logical flag on whether to draw the sides. This will automatically be set to `TRUE` | |
| 734 | #' if `base = TRUE` and the `base_height` is less than `vertical_offset`. | |
| 735 | #' @param vertical_offset Default `0`. The vertical offset of the polygon. | |
| 736 | #' @param base Default `TRUE`. A logical flag that controls whether to generate the bottom of the polygon. | |
| 737 | #' @param base_height Default `NA`. Height of the base, defaulting to the `min(bevel_heights) + vertical_offset` . | |
| 738 | #' @param progress Default `TRUE`. Whether to display a progress bar. | |
| 739 | #' @param verbose Default `FALSE`. A logical flag to control whether additional timing information should be displayed. | |
| 740 | #' @param scale_all_max Default `FALSE`. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall | |
| 741 | #' max height, or whether to scale each max height to the maximum internal distance in the polygon. | |
| 742 | #' @param raw_offsets Default `FALSE`. A logical flag indicating whether the `bevel_offsets` are already in raw format and do not need to be multiplied by the maximum time of the skeleton. | |
| 743 | #' @param raw_heights Default `FALSE`. A logical flag indicating whether the `bevel_heights` are already in raw format and do not need to be multiplied by the maximum time of the skeleton. | |
| 744 | #' @param double_sided Default `FALSE`. A logical flag that controls whether the polygon should be double-sided. | |
| 745 | #' @param material Default `material_list()`. Interface to set the color/appearance/material options for the resulting `ray_mesh` mesh. | |
| 746 | #' @param bevel_material Default `NA`, uses the material specified in `material`. Interface to set the color/appearance/material options for the resulting `ray_mesh` bevel mesh. | |
| 747 | #' | |
| 748 | #' @return A 3D mesh of the beveled polygon model. | |
| 749 | #' | |
| 750 | #' @import rayvertex | |
| 751 | #' | |
| 752 | #' @export | |
| 753 | #' @examples | |
| 754 | #' # Skeletonize a complex {sf} object and set return_skeleton_polygons = TRUE in | |
| 755 | #' # generate_beveled_polygon(). This returns skeleton object with polygons included, which | |
| 756 | #' # allows for quickly generating 3D models with different bevels. | |
| 757 | #' if(run_docs_raybevel()) { | |
| 758 | #' library(rayrender) | |
| 759 | #' library(rayvertex) | |
| 760 | #' us_states = spData::us_states | |
| 761 | #' cali = us_states[us_states$NAME == "California",] | |
| 762 | #' cali_skeleton = skeletonize(cali) | |
| 763 | #' plot_skeleton(cali_skeleton) | |
| 764 | #' # We add manual offsets to ensure that the polygon can be morphed all along its interior | |
| 765 | #' bevel = generate_bevel(manual_offsets = seq(0,1,by=0.01), max_height=0.5) | |
| 766 | #' bevel_model_cali = generate_beveled_polygon(cali_skeleton, | |
| 767 | #' bevel_offsets = bevel, | |
| 768 | #' return_skeleton_polygons = TRUE) | |
| 769 | #' | |
| 770 | #' bevel_new = change_polygon_bevel(bevel_model_cali, | |
| 771 | #' bevel_offsets = generate_bevel(max_height=0.5, | |
| 772 | #' bevel_end=0.5)) |> | |
| 773 | #' center_mesh() | |
| 774 | #' | |
| 775 | #' scene_base = xz_rect(xwidth=100,zwidth=100, | |
| 776 | #' material=diffuse(color="grey20", checkercolor="white")) |> | |
| 777 | #' add_object(sphere(y=8,z=10,x=-3,material=light(intensity=100))) |> | |
| 778 | #' add_object(sphere(y=800,z=10,x=-3,radius=100,material=light(intensity=5))) | |
| 779 | #' | |
| 780 | #' raymesh_model(bevel_new, y=0.5, override_material = TRUE, | |
| 781 | #' material = diffuse(color="purple")) |> | |
| 782 | #' add_object(scene_base) |> | |
| 783 | #' render_scene(lookfrom=c(0,30,-10), samples=16, | |
| 784 | #' width=800,height=800,fov=0,ortho_dimensions=c(12,12)) | |
| 785 | #' } | |
| 786 | #' # Change to a smooth bevel | |
| 787 | #' if(run_docs_raybevel()) { | |
| 788 | #' new_bevel = generate_bevel("circular", bevel_start = 0, bevel_end=1) | |
| 789 | #' bevel_new = change_polygon_bevel(bevel_model_cali, | |
| 790 | #' bevel_offsets = new_bevel, solid ) |> | |
| 791 | #' center_mesh() | |
| 792 | #' raymesh_model(bevel_new, override_material = TRUE, y=1,material = diffuse(color="purple")) |> | |
| 793 | #' add_object(scene_base) |> | |
| 794 | #' render_scene(lookfrom=c(0,30,-10), samples=16, | |
| 795 | #' width=800,height=800,fov=0,ortho_dimensions=c(12,12)) | |
| 796 | #' } | |
| 797 | #' | |
| 798 | #' # Make a complex bevel | |
| 799 | #' if(run_docs_raybevel()) { | |
| 800 | #' complex_coords = generate_complex_bevel( | |
| 801 | #' bevel_type = c("angled","flat", "angled", "flat"), | |
| 802 | #' bevel_start = head(seq(0,1,by=0.05),-1), | |
| 803 | #' bevel_end = tail(seq(0,1,by=0.05),-1), | |
| 804 | #' overall_height = 1, | |
| 805 | #' angle = c(45,45,15,15), | |
| 806 | #' reverse = c(FALSE, FALSE,TRUE,TRUE), | |
| 807 | #' plot_bevel = TRUE | |
| 808 | #' ) | |
| 809 | #' bevel_new = change_polygon_bevel(bevel_model_cali, | |
| 810 | #' bevel_offsets = complex_coords) |> | |
| 811 | #' center_mesh() | |
| 812 | #' raymesh_model(bevel_new, override_material = TRUE, y=1,material = diffuse(color="purple")) |> | |
| 813 | #' add_object(scene_base) |> | |
| 814 | #' render_scene(lookfrom=c(0,30,-20), samples=16, | |
| 815 | #' width=800,height=800,fov=0,ortho_dimensions=c(12,12)) | |
| 816 | #' } | |
| 817 | #' | |
| 818 | #' # Quickly generate new bevels to inflate California like a balloon using the arctan function. | |
| 819 | #' if(run_docs_raybevel()) { | |
| 820 | #' inflate_california = function(magnitudes) { | |
| 821 | #' for(val in magnitudes) { | |
| 822 | #' bevel_new = change_polygon_bevel(bevel_model_cali, | |
| 823 | #' bevel_heights = 1/2*atan(seq(0,val,length.out=100)), | |
| 824 | #' bevel_offsets = seq(0,1, length.out=100), | |
| 825 | #' base = TRUE) |> | |
| 826 | #' translate_mesh(c(-120.49,0,-38.72)) | |
| 827 | #' raymesh_model(bevel_new, y = 0, override_material = TRUE, | |
| 828 | #' material = glossy(color="darkred")) |> | |
| 829 | #' add_object(scene_base) |> | |
| 830 | #' add_object(sphere(x=-30,z=30,y=18,radius=30,material=light(color="white", intensity=5))) |> | |
| 831 | #' render_scene(lookfrom=c(-1, 28, -20.32), lookat=c(-1, 1.46, -2), | |
| 832 | #' samples=16, width=800, height=800, fov=20) | |
| 833 | #' } | |
| 834 | #' } | |
| 835 | #' inflate_california(c(1,4,16,64)) | |
| 836 | #' } | |
| 837 | change_polygon_bevel = function(skeleton_polygons, | |
| 838 | bevel_offsets = NULL, | |
| 839 | bevel_heights = NULL, | |
| 840 | set_max_height = FALSE, | |
| 841 | max_height = 1, | |
| 842 | vertical_offset = 0, | |
| 843 | base = TRUE, | |
| 844 | base_height = NA, | |
| 845 | raw_offsets = FALSE, | |
| 846 | raw_heights = FALSE, | |
| 847 | swap_yz = TRUE, | |
| 848 | progress = TRUE, | |
| 849 | sides = FALSE, | |
| 850 | double_sided = FALSE, | |
| 851 | scale_all_max = FALSE, | |
| 852 | material = material_list(), | |
| 853 | bevel_material = NA, | |
| 854 | verbose = FALSE) { | |
| 855 | ! | if(run_docs_raybevel() || !interactive()) { |
| 856 | ! | progress = FALSE |
| 857 | } | |
| 858 | ! | if(!is.list(bevel_material)) { |
| 859 | ! | bevel_material = material |
| 860 | } | |
| 861 | ! | init_time() |
| 862 | ! | if(inherits(skeleton_polygons, "rayskeleton_list_polygons")) { |
| 863 | ! | pb = progress::progress_bar$new( |
| 864 | ! | format = ":current/:total Generating polygon [:bar] eta: :eta", |
| 865 | ! | total = length(skeleton_polygons), clear = TRUE, width = 60) |
| 866 | ! | meshlist = list() |
| 867 | ! | counter = 1 |
| 868 | ! | if(length(vertical_offset) == 1) { |
| 869 | ! | vertical_offset = rep(vertical_offset,length(skeleton_polygons)) |
| 870 | } | |
| 871 | ! | if(length(max_height) == 1) { |
| 872 | ! | if(scale_all_max) { |
| 873 | ! | max_height = rep(max_height,length(skeleton_polygons)) |
| 874 | } else { | |
| 875 | #Calculate proportional maximum heights | |
| 876 | ! | single_max_heights = unlist(lapply(skeleton_polygons, \(x) max(x$nodes$time))) |
| 877 | ! | max_height = single_max_heights/max(single_max_heights) * max_height |
| 878 | } | |
| 879 | } | |
| 880 | ! | for(j in seq_len(length(skeleton_polygons))) { |
| 881 | ! | if(progress) { |
| 882 | ! | pb$tick() |
| 883 | } | |
| 884 | ! | meshlist[[counter]] = change_polygon_bevel(skeleton_polygons[[j]], |
| 885 | ! | bevel_offsets = bevel_offsets, |
| 886 | ! | bevel_heights = bevel_heights, |
| 887 | ! | base = base, |
| 888 | ! | vertical_offset = vertical_offset[j], |
| 889 | ! | max_height = max_height[j], |
| 890 | ! | raw_offsets = raw_offsets, |
| 891 | ! | raw_heights = raw_heights, |
| 892 | ! | sides = sides, |
| 893 | ! | progress = FALSE, |
| 894 | ! | double_sided = double_sided, |
| 895 | ! | base_height = base_height, |
| 896 | ! | bevel_material = bevel_material, |
| 897 | ! | material = material, |
| 898 | ! | swap_yz = swap_yz) |
| 899 | ! | counter = counter + 1 |
| 900 | } | |
| 901 | ! | return(scene_from_list(meshlist)) |
| 902 | } | |
| 903 | ! | if(inherits(skeleton_polygons, "ray_mesh")) { |
| 904 | ! | return(skeleton_polygons) |
| 905 | } | |
| 906 | ! | if(!inherits(skeleton_polygons, "rayskeleton_polygon")) { |
| 907 | ! | stop("`skeleton_polygon` must be of class `rayskeleton_polygon`") |
| 908 | } | |
| 909 | ! | max_time = max(skeleton_polygons$links$destination_time) |
| 910 | ! | if(is.list(bevel_offsets) && |
| 911 | ! | !is.null(bevel_offsets$x) && |
| 912 | ! | !is.null(bevel_offsets$y)) { |
| 913 | ! | bevel_heights = bevel_offsets$y |
| 914 | ! | bevel_offsets = bevel_offsets$x |
| 915 | # if(set_max_height) { | |
| 916 | # warning("`set_max_height` is ignored when passing in bevel curve--set the max height when generating the bevel.") | |
| 917 | # set_max_height = FALSE | |
| 918 | # } | |
| 919 | } | |
| 920 | ! | if(!raw_offsets) { |
| 921 | ! | if(any(bevel_offsets > 1 | bevel_offsets < 0)) { |
| 922 | ! | stop("If using percentage offsets, all `bevel_offsets` must be between 0 and 1.") |
| 923 | } | |
| 924 | ! | bevel_offsets_pct = bevel_offsets |
| 925 | ! | bevel_offsets = bevel_offsets * max_time |
| 926 | } else { | |
| 927 | ! | bevel_offsets_pct = bevel_offsets / max_time |
| 928 | } | |
| 929 | #Offsets should be in units of the coordinate system at this point | |
| 930 | ! | non_zero_offsets = bevel_offsets[bevel_offsets > 0] |
| 931 | ! | if(all(non_zero_offsets >= max_time)) { |
| 932 | ! | interpolated_data = stats::approx(x = bevel_offsets, y = bevel_heights, |
| 933 | ! | xout = c(0,max_time)) |
| 934 | ! | bevel_offsets = c(0,max_time) |
| 935 | ! | bevel_offsets_pct = c(0,1) |
| 936 | ! | bevel_heights = interpolated_data$y |
| 937 | } | |
| 938 | ! | if(!raw_heights) { |
| 939 | ! | bevel_heights = bevel_heights * max_time |
| 940 | } | |
| 941 | ! | if(is.na(base_height)) { |
| 942 | ! | height_range = range(bevel_heights) |
| 943 | ! | if(base || double_sided) { |
| 944 | ! | min_offset = (height_range[2]-height_range[1]) * 1e-6 |
| 945 | } else { | |
| 946 | ! | min_offset = 0 |
| 947 | } | |
| 948 | ! | base_height = min(bevel_heights) + min_offset + vertical_offset |
| 949 | } | |
| 950 | ||
| 951 | ! | stopifnot(length(vertical_offset) == 1) |
| 952 | ||
| 953 | ! | reordered_new_ss = skeleton_polygons |
| 954 | ! | old_bevel_offsets = unique(attr(reordered_new_ss, "bevel_offsets")) |
| 955 | ! | polygon_ind = attr(reordered_new_ss, "polygons") |
| 956 | ! | last_height = bevel_heights[length(bevel_heights)] |
| 957 | ! | if(bevel_offsets_pct[length(bevel_offsets_pct)] != 1 ) { |
| 958 | ! | bevel_offsets_pct = c(bevel_offsets_pct,1) |
| 959 | ! | bevel_heights_with_last = c(bevel_heights,last_height) |
| 960 | } else { | |
| 961 | ! | bevel_heights_with_last = bevel_heights |
| 962 | } | |
| 963 | ! | interpolated_data = stats::approx(x = bevel_offsets_pct, y = bevel_heights_with_last, xout = old_bevel_offsets, |
| 964 | ! | rule = 2) |
| 965 | ! | bevel_heights = interpolated_data$y |
| 966 | ! | bevel_offsets = old_bevel_offsets * max_time |
| 967 | ! | bevel_offsets = bevel_offsets[order(bevel_offsets)] |
| 968 | ! | bevel_heights = bevel_heights[order(bevel_offsets)] |
| 969 | ||
| 970 | ! | height_range = range(bevel_heights) |
| 971 | ! | height_range = height_range[2]-height_range[1] |
| 972 | ! | if(set_max_height) { |
| 973 | ! | min_height = min(bevel_heights) |
| 974 | ! | offset_bevel_heights = bevel_heights - min_height |
| 975 | ! | offset_bevel_heights = max_height * offset_bevel_heights / height_range + min_height |
| 976 | ! | height_range = max_height |
| 977 | ! | bevel_heights = offset_bevel_heights |
| 978 | } | |
| 979 | ! | stopifnot(length(vertical_offset) == 1) |
| 980 | ! | stopifnot(vertical_offset >= 0) |
| 981 | ! | bevel_heights = bevel_heights + vertical_offset |
| 982 | ||
| 983 | ! | valid_bevels = bevel_offsets <= max_time & bevel_offsets > 0 |
| 984 | ! | zero_height_val = bevel_heights[1] |
| 985 | ! | bevel_offsets_valid = bevel_offsets[valid_bevels] |
| 986 | ! | bevel_heights_valid = bevel_heights[valid_bevels] |
| 987 | ! | stopifnot(length(bevel_offsets_valid) == length(bevel_heights_valid)) |
| 988 | #Remove extremely close offsets (usually arising from floating point error) | |
| 989 | ! | for(i in rev(seq_len(length(bevel_offsets_valid)))) { |
| 990 | ! | all_other_offsets = bevel_offsets_valid[-i] |
| 991 | ! | if(any(abs(bevel_offsets_valid[i] - all_other_offsets) < 1e-14, na.rm = TRUE)) { |
| 992 | ! | bevel_offsets_valid[i] = NA |
| 993 | } | |
| 994 | } | |
| 995 | ! | remove_close_vals = !is.na(bevel_offsets_valid) |
| 996 | ! | bevel_offsets_valid = bevel_offsets_valid[remove_close_vals] |
| 997 | ! | bevel_heights_valid = bevel_heights_valid[remove_close_vals] |
| 998 | ||
| 999 | ! | nodes = reordered_new_ss$nodes |
| 1000 | ! | index_list = list() |
| 1001 | ! | for(i in seq_len(length(polygon_ind))) { |
| 1002 | ! | tmp_ind = polygon_ind[[i]] |
| 1003 | ! | tmp_poly = nodes[tmp_ind,2:3] |
| 1004 | ! | index_list[[i]] = matrix(tmp_ind[decido::earcut(tmp_poly)], byrow = TRUE, ncol = 3) |
| 1005 | } | |
| 1006 | ! | indices_all = do.call("rbind",index_list) |
| 1007 | ! | xyz = nodes[,2:4] |
| 1008 | ||
| 1009 | ! | new_xyz = xyz |
| 1010 | ||
| 1011 | ! | bevel_offsets_polys = c(0,bevel_offsets_valid) |
| 1012 | ! | bevel_heights_polys = c(zero_height_val,bevel_heights_valid) |
| 1013 | ||
| 1014 | ! | if(bevel_offsets_polys[length(bevel_offsets_polys)] != max_time) { |
| 1015 | ! | bevel_offsets_with_max = c(bevel_offsets_polys, max_time) |
| 1016 | ! | bevel_heights_with_max = c(bevel_heights_polys, max(bevel_heights_polys)) |
| 1017 | } else { | |
| 1018 | ! | bevel_offsets_with_max = bevel_offsets_polys |
| 1019 | ! | bevel_heights_with_max = bevel_heights_polys |
| 1020 | } | |
| 1021 | ! | side_top = bevel_heights_with_max[1] |
| 1022 | ||
| 1023 | ! | new_xyz[,3] = stats::approx(x=bevel_offsets_with_max,y=bevel_heights_with_max, xout = xyz[,3], rule=2)$y |
| 1024 | ||
| 1025 | ! | xyz = new_xyz |
| 1026 | ! | colnames(xyz) = c("x","y","z") |
| 1027 | ||
| 1028 | ! | original_verts = attr(reordered_new_ss,"original_vertices") |
| 1029 | ! | original_holes = attr(reordered_new_ss,"original_holes") |
| 1030 | ||
| 1031 | ! | mesh = construct_mesh(vertices = as.matrix(xyz), |
| 1032 | ! | indices = as.matrix(indices_all)-1)|> |
| 1033 | ! | set_material(bevel_material) |
| 1034 | ||
| 1035 | ! | if(double_sided) { |
| 1036 | ! | xyzflip = xyz |
| 1037 | ! | xyzflip[,3] = -xyzflip[,3] |
| 1038 | ! | indices_flip = indices_all[,3:1,drop=FALSE] |
| 1039 | ! | double_mesh = construct_mesh(vertices = as.matrix(xyzflip), |
| 1040 | ! | indices = as.matrix(indices_flip)-1)|> |
| 1041 | ! | set_material(bevel_material) |
| 1042 | } | |
| 1043 | ! | if(base && !double_sided) { |
| 1044 | ! | if(length(original_holes) > 0) { |
| 1045 | ! | holes = c(0,utils::head(cumsum(unlist(lapply(original_holes,nrow))),-1)) + nrow(original_verts) + 1 |
| 1046 | ! | hole_mat = do.call("rbind", original_holes) |
| 1047 | ! | original_verts_holes = rbind(original_verts, hole_mat) |
| 1048 | } else { | |
| 1049 | ! | holes = 0 |
| 1050 | ! | original_verts_holes = original_verts |
| 1051 | } | |
| 1052 | ! | base_indices = matrix(decido::earcut(original_verts_holes, holes = holes), byrow = TRUE, ncol=3) |
| 1053 | ! | base_indices = base_indices[,3:1,drop = FALSE] |
| 1054 | ! | original_verts_base = cbind(original_verts_holes, rep(0, nrow(original_verts_holes))) |
| 1055 | ! | base_mesh = construct_mesh(vertices = as.matrix(original_verts_base), |
| 1056 | ! | indices = as.matrix(base_indices)-1) |> |
| 1057 | ! | set_material(material) |
| 1058 | ||
| 1059 | ! | mesh = mesh |> |
| 1060 | ! | add_shape(base_mesh) |
| 1061 | } | |
| 1062 | ! | if(double_sided) { |
| 1063 | ! | mesh = add_shape(mesh, double_mesh) |
| 1064 | } | |
| 1065 | ! | if((sides || base || double_sided) && |
| 1066 | ! | ((!double_sided && side_top > 0) || (double_sided && side_top > 0))) { |
| 1067 | ! | if(!double_sided) { |
| 1068 | ! | side_mesh = extrude_sides(original_verts, original_holes, bottom = 0, top = side_top) |
| 1069 | } else { | |
| 1070 | ! | side_mesh = extrude_sides(original_verts, original_holes, bottom = -side_top, top = side_top) |
| 1071 | } | |
| 1072 | ! | side_mesh = side_mesh |> |
| 1073 | ! | set_material(material) |
| 1074 | ! | mesh = add_shape(mesh, side_mesh) |
| 1075 | } | |
| 1076 | ! | if(swap_yz) { |
| 1077 | ! | mesh = swap_yz(mesh) |
| 1078 | } | |
| 1079 | ! | if(!is.na(base_height)) { |
| 1080 | ! | if(swap_yz) { |
| 1081 | ! | mesh = translate_mesh(mesh, c(0,base_height,0)) |
| 1082 | } else { | |
| 1083 | ! | mesh = translate_mesh(mesh, c(0,0,base_height)) |
| 1084 | } | |
| 1085 | } | |
| 1086 | ! | print_time(verbose, "Generated mesh") |
| 1087 | ||
| 1088 | ! | return(mesh) |
| 1089 | } |
| 1 | #' @title Run Documentation | |
| 2 | #' | |
| 3 | #' @description This function determines if the examples are being run in pkgdown. It is not meant to be called by the user. | |
| 4 | #' | |
| 5 | #' @export | |
| 6 | #' | |
| 7 | #' @return Boolean value. | |
| 8 | #' @examples | |
| 9 | #' # See if the documentation should be run. | |
| 10 | #' run_docs_raybevel() | |
| 11 | run_docs_raybevel = function() { | |
| 12 | 321x | return(identical(Sys.getenv("IN_PKGDOWN"), "true") && |
| 13 | 321x | length(find.package("ggplot2",quiet = TRUE)) > 0 && |
| 14 | 321x | length(find.package("spData",quiet = TRUE)) > 0) |
| 15 | } |
| 1 | #' Modify bevel data using straight skeleton | |
| 2 | #' | |
| 3 | #' | |
| 4 | #' @keywords internal | |
| 5 | #' @return list. Modified bevel_height and bevel_offset vectors. | |
| 6 | modify_bevel_with_skeleton = function(bevel_offsets, bevel_heights, straight_skeleton) { | |
| 7 | ! | if(is.list(bevel_offsets) && |
| 8 | ! | !is.null(bevel_offsets$x) && |
| 9 | ! | !is.null(bevel_offsets$y)) { |
| 10 | ! | bevel_heights = bevel_offsets$y |
| 11 | ! | bevel_offsets = bevel_offsets$x |
| 12 | } | |
| 13 | # Extract skeleton's nodes that are not already in the bevel | |
| 14 | ! | unique_times = unique(straight_skeleton$nodes$time) |
| 15 | ! | unique_times = setdiff(unique_times, bevel_offsets) |
| 16 | ! | unique_times = unique_times[unique_times < max(bevel_offsets)] |
| 17 | ||
| 18 | # Initialize new bevel data vectors | |
| 19 | ! | new_bevel_height = bevel_heights |
| 20 | ! | new_bevel_offset = bevel_offsets |
| 21 | ||
| 22 | ! | for(time in unique_times) { |
| 23 | # Identify the indices where new values should be inserted | |
| 24 | ! | insert_idx = sum(new_bevel_offset < time) + 1 |
| 25 | ||
| 26 | # Compute interpolated bevel height | |
| 27 | ! | if (insert_idx > 1 && insert_idx <= length(new_bevel_height)) { |
| 28 | ! | prev_height = new_bevel_height[insert_idx - 1] |
| 29 | ! | next_height = new_bevel_height[insert_idx] |
| 30 | ! | prev_offset = new_bevel_offset[insert_idx - 1] |
| 31 | ! | next_offset = new_bevel_offset[insert_idx] |
| 32 | ! | offset_range = next_offset - prev_offset |
| 33 | ! | height_range = next_height - prev_height |
| 34 | ! | if(height_range == 0) { |
| 35 | ! | next |
| 36 | } | |
| 37 | ! | t = (time - prev_offset)/offset_range |
| 38 | ! | interpolated_height = (1 - t) * prev_height + t * next_height |
| 39 | } else { | |
| 40 | # If the new time is outside the existing range, no interpolation is needed | |
| 41 | ! | interpolated_height = time |
| 42 | } | |
| 43 | ||
| 44 | # Insert new data points into the bevel vectors | |
| 45 | ! | new_bevel_height = c(new_bevel_height[1:(insert_idx - 1)], interpolated_height, new_bevel_height[insert_idx:length(new_bevel_height)]) |
| 46 | ! | new_bevel_offset = c(new_bevel_offset[1:(insert_idx - 1)], time, new_bevel_offset[insert_idx:length(new_bevel_offset)]) |
| 47 | } | |
| 48 | ||
| 49 | ! | return(list(x = new_bevel_offset, y = new_bevel_height)) |
| 50 | } |
| 1 | #' Plot the Straight Skeleton of a Polygon | |
| 2 | #' | |
| 3 | #' This function visualizes the straight skeleton derived from a given polygon. | |
| 4 | #' The original polygon (with holes if present) is plotted in black, while the | |
| 5 | #' straight skeleton is plotted in red. | |
| 6 | #' | |
| 7 | #' @param skeleton A list object of class 'rayskeleton' containing the straight | |
| 8 | #' skeleton details. It should have 'nodes' and 'links' as its primary components. | |
| 9 | #' @param use_arrow Default `TRUE`. A logical value indicating whether or not to use arrows | |
| 10 | #' to represent the links of the straight skeleton. Default is TRUE. | |
| 11 | #' @param use_points Default `TRUE`. Whether to plot the vertex points as well. | |
| 12 | #' @param xlim Default`c(0,1)`. A numeric vector of length 2 specifying the x-limits of the | |
| 13 | #' plot in the form `c(min, max)`. These are proportional limits relative | |
| 14 | #' to the bounding box around the skeleton. | |
| 15 | #' @param ylim Default `c(0,1)`. A numeric vector of length 2 specifying the y-limits of the | |
| 16 | #' plot in the form c(min, max). These are proportional limits relative | |
| 17 | #' to the bounding box around the skeleton. | |
| 18 | #' @param arrow_color Default `"red"`. Color of the arrows. | |
| 19 | #' @param polygon_color Default `"black"`. Color of the polygon. | |
| 20 | #' @param size Default `1`. Size of the vertex points. | |
| 21 | #' @param arrow_size Default `1`. Scales the arrow size. | |
| 22 | #' @param highlight_links Default `NULL`. A numeric vector indicating which links | |
| 23 | #' (by their index) to highlight. If specified, the corresponding links will | |
| 24 | #' be colored with the `highlight_color`. | |
| 25 | #' @param highlight_color Default `"purple"`. Color of the highlighted links. | |
| 26 | #' @param return_layers Default `FALSE`, plots the figure. If `TRUE`, this will instead | |
| 27 | #' return a list of the ggplot layers. | |
| 28 | #' | |
| 29 | #' @details The function uses the `ggplot2` package for plotting. The straight skeleton | |
| 30 | #' is visualized based on the details provided in the `skeleton` object. | |
| 31 | #' The original polygon and holes are plotted based on attributes stored | |
| 32 | #' in the `skeleton` object. | |
| 33 | #' | |
| 34 | #' @return A ggplot object visualizing the straight skeleton and the original polygon. | |
| 35 | #' @export | |
| 36 | #' @examples | |
| 37 | #' # Assuming skeleton1 is already defined as in the previous example | |
| 38 | #' # Outer polygon | |
| 39 | #' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE) | |
| 40 | #' # Holes inside the polygon | |
| 41 | #' hole1 = matrix(c(1,1, 1,2, 2,2, 2,1, 1,1), ncol = 2, byrow = TRUE) | |
| 42 | #' hole2 = matrix(c(5,5, 5,6, 6,6, 6,5, 5,5), ncol = 2, byrow = TRUE) | |
| 43 | #' skeleton = skeletonize(vertices, holes = list(hole1, hole2)) | |
| 44 | #' if(run_docs_raybevel()) { | |
| 45 | #' plot_skeleton(skeleton) | |
| 46 | #' } | |
| 47 | #' # Skeletonize and plot an {sf} object | |
| 48 | #' if(run_docs_raybevel()) { | |
| 49 | #' us_states = spData::us_states | |
| 50 | #' texas = us_states[us_states$NAME == "Texas",] | |
| 51 | #' plot_skeleton(skeletonize(texas)) | |
| 52 | #' } | |
| 53 | #' # Highlighting certain links in the skeleton | |
| 54 | #' max_links =which(skeleton$links$destination_time == max(skeleton$links$destination_time)) | |
| 55 | #' if(run_docs_raybevel()) { | |
| 56 | #' plot_skeleton(skeleton, highlight_links = max_links, highlight_color = "green") | |
| 57 | #' } | |
| 58 | plot_skeleton = function(skeleton, use_arrow = TRUE, use_points = TRUE, xlim = c(0,1), ylim = c(0,1), | |
| 59 | arrow_color = "red", polygon_color = "black", size = 1, | |
| 60 | arrow_size = 0.05, highlight_links = NULL, highlight_color = "green", | |
| 61 | return_layers = FALSE) { | |
| 62 | ! | if(!(length(find.package("ggplot2", quiet = TRUE)) > 0)) { |
| 63 | ! | stop("{ggplot2} package required for plot_skeleton()") |
| 64 | } | |
| 65 | ! | is_highlighted = mid_x = mid_y = x = y = xend = yend = NULL |
| 66 | ||
| 67 | # Check if skeleton is valid | |
| 68 | ! | if (!inherits(skeleton, c("rayskeleton","rayskeleton_polygon", "rayskeleton_list"))) { |
| 69 | ! | stop(sprintf("Invalid input: The input is not of class: '%s'", |
| 70 | ! | paste0(c("rayskeleton","rayskeleton_polygon", "rayskeleton_list"), collapse=", "))) |
| 71 | } | |
| 72 | ||
| 73 | #Import external functions from suggested packages | |
| 74 | ! | aes = ggplot2::aes |
| 75 | ! | ggplot = ggplot2::ggplot |
| 76 | ! | theme_void = ggplot2::theme_void |
| 77 | ! | geom_point = ggplot2::geom_point |
| 78 | ! | geom_segment = ggplot2::geom_segment |
| 79 | ! | geom_point = ggplot2::geom_point |
| 80 | ! | scale_color_manual = ggplot2::scale_color_manual |
| 81 | ! | geom_polygon = ggplot2::geom_polygon |
| 82 | ! | theme = ggplot2::theme |
| 83 | ! | coord_fixed = ggplot2::coord_fixed |
| 84 | ||
| 85 | # Create base ggplot object | |
| 86 | # p = ggplot() + theme_void() | |
| 87 | ! | p = list() |
| 88 | ! | if(!inherits(skeleton, "rayskeleton_list")) { |
| 89 | ! | skeleton_all = list(skeleton) |
| 90 | } else { | |
| 91 | ! | skeleton_all = skeleton |
| 92 | } | |
| 93 | ! | final_links_list = list() |
| 94 | ! | final_nodes_list = list() |
| 95 | ! | for(i in seq_along(skeleton_all)) { |
| 96 | ! | skeleton = skeleton_all[[i]] |
| 97 | ! | final_nodes_list[[i]] = skeleton$nodes |
| 98 | ||
| 99 | ! | skeleton$links$mid_x = (skeleton$nodes[skeleton$links$source, 'x'] + skeleton$nodes[skeleton$links$destination, 'x']) / 2 |
| 100 | ! | skeleton$links$mid_y = (skeleton$nodes[skeleton$links$source, 'y'] + skeleton$nodes[skeleton$links$destination, 'y']) / 2 |
| 101 | ! | skeleton$links$x = skeleton$nodes[skeleton$links$source, 'x'] |
| 102 | ! | skeleton$links$y = skeleton$nodes[skeleton$links$source, 'y'] |
| 103 | ! | skeleton$links$xend = skeleton$nodes[skeleton$links$destination, 'x'] |
| 104 | ! | skeleton$links$yend = skeleton$nodes[skeleton$links$destination, 'y'] |
| 105 | ! | skeleton$links$is_highlighted <- ifelse(seq_len(nrow(skeleton$links)) %in% highlight_links, TRUE, FALSE) |
| 106 | ! | final_links_list[[i]] = skeleton$links |
| 107 | } | |
| 108 | ! | final_links = do.call("rbind", final_links_list) |
| 109 | ! | final_nodes = do.call("rbind", final_nodes_list) |
| 110 | ||
| 111 | # Plot skeleton nodes | |
| 112 | ! | if(use_points) { |
| 113 | ! | p[[length(p) + 1]] = geom_point(data = final_nodes, |
| 114 | ! | aes(x = x, y = y), |
| 115 | ! | color = polygon_color, size = size) |
| 116 | } | |
| 117 | ||
| 118 | # Plot skeleton links (arrows or segments) | |
| 119 | ! | if (use_arrow) { |
| 120 | ! | p[[length(p) + 1]] = geom_segment(data = final_links, |
| 121 | ! | aes(x = x, |
| 122 | ! | y = y, |
| 123 | ! | xend = mid_x, |
| 124 | ! | yend = mid_y, |
| 125 | ! | color = is_highlighted), |
| 126 | ! | arrow = grid::arrow(type = "closed", length = grid::unit(arrow_size, "inches"))) |
| 127 | ! | p[[length(p) + 1]] = geom_segment(data = final_links, |
| 128 | ! | aes(x = mid_x, |
| 129 | ! | y = mid_y, |
| 130 | ! | xend = xend, |
| 131 | ! | yend = yend, |
| 132 | ! | color = is_highlighted)) |
| 133 | } else { | |
| 134 | ! | p[[length(p) + 1]] = geom_segment(data = final_links, |
| 135 | ! | aes(x = x, |
| 136 | ! | y = y, |
| 137 | ! | xend = xend, |
| 138 | ! | yend = yend, |
| 139 | ! | color = is_highlighted)) |
| 140 | } | |
| 141 | ! | p[[length(p) + 1]] = scale_color_manual(values=c(arrow_color, highlight_color)) |
| 142 | ! | p[[length(p) + 1]] = theme(legend.position = "none") |
| 143 | ||
| 144 | # Plot original polygon | |
| 145 | ! | for(i in seq_along(skeleton_all)) { |
| 146 | ! | skeleton = skeleton_all[[i]] |
| 147 | ! | original_vertices = attr(skeleton, "original_vertices") |
| 148 | ! | colnames(original_vertices) = c("x","y") |
| 149 | ! | p[[length(p) + 1]] = geom_polygon(data = data.frame(original_vertices), |
| 150 | ! | aes(x = x, y = y), |
| 151 | ! | color = polygon_color, fill = NA) |
| 152 | ||
| 153 | # Plot holes if any | |
| 154 | ! | original_holes = attr(skeleton, "original_holes") |
| 155 | ! | if (length(original_holes) > 0) { |
| 156 | ! | for (hole in original_holes) { |
| 157 | ! | hole = data.frame(hole) |
| 158 | ! | colnames(hole) = c("x","y") |
| 159 | ||
| 160 | ! | p[[length(p) + 1]] = geom_polygon(data = hole, |
| 161 | ! | aes(x = x, y = y), |
| 162 | ! | color = polygon_color, fill = NA) |
| 163 | } | |
| 164 | } | |
| 165 | } | |
| 166 | ! | if(!return_layers) { |
| 167 | # Adjust plot limits and maintain aspect ratio | |
| 168 | ! | p[[length(p) + 1]] = coord_fixed(ratio = 1) |
| 169 | ! | p[[length(p) + 1]] = theme_void() |
| 170 | ! | p[[length(p) + 1]] = theme(legend.position = "none") |
| 171 | ||
| 172 | ! | return(ggplot() + p) |
| 173 | ||
| 174 | } else { | |
| 175 | ! | return(p) |
| 176 | } | |
| 177 | } |
| 1 | #' Skeletonize a polygon | |
| 2 | #' | |
| 3 | #' This function generates a straight skeleton of a polygon, based on a set of vertices and holes. | |
| 4 | #' It uses the CGAL library to create the straight skeleton using exact arithmetic, | |
| 5 | #' and then parses that file into a more manageable format. | |
| 6 | #' | |
| 7 | #' @param vertices Default `NULL`. A matrix of x and y coordinates representing the vertices of the polygon in counter-clockwise (CCW) order. | |
| 8 | #' @param holes Default `list()`. A list of matrices, each representing a hole in the polygon with x and y coordinates in clockwise (CW) order. | |
| 9 | #' @param debug Default `FALSE`. A logical flag that controls whether debugging information should be printed. | |
| 10 | #' @param return_raw_ss Default `FALSE`. A logical flag that controls whether the raw straight skeleton should be returned. | |
| 11 | #' @param merge_nodes_tolerance Default `1e-5`. A numeric value specifying the tolerance level for merging nodes. It should be a value between 0 and 1. | |
| 12 | #' This value species the size of the grid that the nodes are snapped to determining identical nodes. | |
| 13 | #' @param progress Default `TRUE`. A logical flag that controls whether a progress bar should be displayed while skeletonizing. | |
| 14 | #' | |
| 15 | #' @return If `return_raw_ss` is FALSE, a list with two data frames, 'nodes' and 'links', which represent the nodes and edges of the straight skeleton, respectively. | |
| 16 | #' If `return_raw_ss` is TRUE, a data frame representing the raw straight skeleton is returned. | |
| 17 | #' If the polygon is not simple, a warning is issued and NULL is returned. | |
| 18 | #' | |
| 19 | #' @export | |
| 20 | #' @examples | |
| 21 | #' # Example 1: Simple rectangle polygon with no holes | |
| 22 | #' vertices1 = matrix(c(0,0, 4,0, 4,3, 0,3, 0,0), ncol = 2, byrow = TRUE) | |
| 23 | #' skeleton1 = skeletonize(vertices1) | |
| 24 | #' if(run_docs_raybevel()){ | |
| 25 | #' plot_skeleton(skeleton1) | |
| 26 | #' } | |
| 27 | #' | |
| 28 | #' # Example 2: Triangle polygon with no holes | |
| 29 | #' vertices2 = matrix(c(0,0, 2,0, 1,2, 0,0), ncol = 2, byrow = TRUE) | |
| 30 | #' skeleton2 = skeletonize(vertices2) | |
| 31 | #' if(run_docs_raybevel()) { | |
| 32 | #' plot_skeleton(skeleton2) | |
| 33 | #' } | |
| 34 | #' | |
| 35 | #' # Example 3: Polygon with a hole | |
| 36 | #' # Outer polygon | |
| 37 | #' vertices3 = matrix(c(0,0, 5,0, 5,5, 0,5, 0,0), ncol = 2, byrow = TRUE) | |
| 38 | #' # Hole inside the polygon | |
| 39 | #' hole3 = matrix(c(1,1, 4,1, 4,4, 1,4, 1,1), ncol = 2, byrow = TRUE)[5:1,] | |
| 40 | #' skeleton3 = skeletonize(vertices3, holes = list(hole3)) | |
| 41 | #' if(run_docs_raybevel()) { | |
| 42 | #' plot_skeleton(skeleton3) | |
| 43 | #' } | |
| 44 | #' | |
| 45 | #' # Example 4: Polygon with multiple holes | |
| 46 | #' # Outer polygon | |
| 47 | #' vertices4 = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE) | |
| 48 | #' # Holes inside the polygon | |
| 49 | #' hole4_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,] | |
| 50 | #' hole4_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,] | |
| 51 | #' skeleton4 = skeletonize(vertices4, holes = list(hole4_1, hole4_2)) | |
| 52 | #' if(run_docs_raybevel()) { | |
| 53 | #' plot_skeleton(skeleton4) | |
| 54 | #' } | |
| 55 | #' | |
| 56 | #' # Example 5: Using debug and returning raw straight skeleton | |
| 57 | #' vertices5 = matrix(c(0,0, 3,0, 3,3, 0,3, 0,0), ncol = 2, byrow = TRUE) | |
| 58 | #' raw_skeleton5 = skeletonize(vertices5, debug = TRUE, return_raw_ss = TRUE) | |
| 59 | #' | |
| 60 | #' # Skeletonize and plot an {sf} object | |
| 61 | #' if(run_docs_raybevel()) { | |
| 62 | #' us_states = spData::us_states | |
| 63 | #' texas = us_states[us_states$NAME == "Texas",] | |
| 64 | #' plot_skeleton(skeletonize(texas)) | |
| 65 | #' } | |
| 66 | skeletonize = function(vertices, holes = list(), debug = FALSE, | |
| 67 | merge_nodes_tolerance = 1e-5, | |
| 68 | return_raw_ss = FALSE, | |
| 69 | progress = TRUE) { | |
| 70 | 144x | if(inherits(vertices,"data.frame") && !inherits(vertices,"sf")) { |
| 71 | ! | vertices = as.matrix(vertices) |
| 72 | } | |
| 73 | 144x | stopifnot(merge_nodes_tolerance >= 0 && merge_nodes_tolerance < 1) |
| 74 | 144x | if(inherits(vertices, "sf")) { |
| 75 | 5x | pb = progress::progress_bar$new( |
| 76 | 5x | format = ":current/:total skeletonizing [:bar] eta: :eta", |
| 77 | 5x | total = nrow(vertices), clear = TRUE, width = 60) |
| 78 | 5x | non_empty_geometry = list() |
| 79 | 5x | cntr = 1 |
| 80 | 5x | list_idx = list() |
| 81 | 5x | for(i in seq_len(length(vertices$geometry))) { |
| 82 | 102x | if(length(vertices$geometry[[i]]) > 0) { |
| 83 | 102x | non_empty_geometry[[cntr]] = vertices$geometry[[i]] |
| 84 | 102x | list_idx[[cntr]] = i |
| 85 | 102x | cntr = cntr + 1 |
| 86 | } | |
| 87 | } | |
| 88 | 5x | all_coords = lapply(non_empty_geometry, sf::st_coordinates) |
| 89 | 5x | is_multipolygon = unlist(lapply(non_empty_geometry, (function(x) inherits(x,"MULTIPOLYGON")))) |
| 90 | 5x | is_polygon = unlist(lapply(non_empty_geometry, (function(x) inherits(x,"POLYGON")))) |
| 91 | ||
| 92 | 5x | ss_list = list() |
| 93 | 5x | counter = 1 |
| 94 | 5x | for(i in seq_len(length(all_coords))) { |
| 95 | 102x | if(progress) { |
| 96 | 102x | pb$tick() |
| 97 | } | |
| 98 | 102x | single_row_geometry = all_coords[[i]] |
| 99 | 102x | if(is_polygon[i]) { |
| 100 | ! | all_features = split(as.data.frame(single_row_geometry)[,c("X","Y","L1")], |
| 101 | ! | list(single_row_geometry[,c("L2")])) |
| 102 | ! | for(j in seq_len(length(all_features))) { |
| 103 | ! | single_feature = all_features[[j]] |
| 104 | ! | exterior_points = single_feature[,"L1"] == 1 |
| 105 | ! | verts = as.matrix(single_feature[exterior_points,c("X","Y")]) |
| 106 | ! | if(all(verts[1,] == verts[nrow(verts),])) { |
| 107 | ! | verts = verts[-nrow(verts),] |
| 108 | } | |
| 109 | ! | hole_mat = single_feature[!exterior_points,] |
| 110 | ! | if(nrow(hole_mat) > 0) { |
| 111 | ! | holes = split(as.data.frame(hole_mat)[,c("X","Y")], |
| 112 | ! | hole_mat[,c("L1")]) |
| 113 | } else { | |
| 114 | ! | holes = list() |
| 115 | } | |
| 116 | ! | if(!is_simple_polygon(verts)) { |
| 117 | ! | warning(sprintf("Row %i in `sf` object not simple polygon, skipping",i)) |
| 118 | ! | next |
| 119 | } | |
| 120 | #Fix orientations | |
| 121 | ! | if(!is_ccw_polygon(as.matrix(verts))) { |
| 122 | ! | verts = verts[rev(seq_len(nrow(verts))),] |
| 123 | } | |
| 124 | ! | for(k in seq_len(length(holes))) { |
| 125 | ! | if(all(holes[[k]][1,] == holes[[k]][nrow(holes[[k]]),])) { |
| 126 | ! | holes[[k]] = holes[[k]][-nrow(holes[[k]]),] |
| 127 | } | |
| 128 | ! | holes[[k]] = as.matrix(holes[[k]]) |
| 129 | ! | if(!is_simple_polygon(as.matrix(holes[[k]]))) { |
| 130 | ! | warning(sprintf("Hole in row %i in `sf` object not simple polygon, skipping", i)) |
| 131 | ! | next |
| 132 | } | |
| 133 | ! | if(is_ccw_polygon(holes[[k]])) { |
| 134 | ! | holes[[k]] = holes[[k]][rev(seq_len(nrow(holes[[k]]))),] |
| 135 | } | |
| 136 | } | |
| 137 | #Skeletonize | |
| 138 | ! | ss_list[[counter]] = skeletonize(as.matrix(verts), debug = debug, |
| 139 | ! | holes = holes, |
| 140 | ! | return_raw_ss = return_raw_ss, |
| 141 | ! | merge_nodes_tolerance = merge_nodes_tolerance) |
| 142 | ! | attr(ss_list[[counter]], "original_sf_row_index") = list_idx[[i]] |
| 143 | ! | counter = counter + 1 |
| 144 | } | |
| 145 | 102x | } else if (is_multipolygon[i]) { |
| 146 | 102x | all_polygons = split(as.data.frame(single_row_geometry)[,c("X", "Y", "L1", "L2")], |
| 147 | 102x | list(single_row_geometry[,c("L3")])) |
| 148 | 102x | for(ii in seq_len(length(all_polygons))) { |
| 149 | 102x | single_polygon = all_polygons[[ii]] |
| 150 | 102x | all_features = split(as.data.frame(single_polygon)[,c("X", "Y", "L1")], |
| 151 | 102x | list(single_polygon[,c("L2")])) |
| 152 | 102x | for(j in seq_len(length(all_features))) { |
| 153 | 137x | single_feature = all_features[[j]] |
| 154 | 137x | exterior_points = single_feature[,"L1"] == 1 |
| 155 | 137x | verts = as.matrix(single_feature[exterior_points,c("X","Y")]) |
| 156 | 137x | if(all(verts[1,] == verts[nrow(verts),])) { |
| 157 | 137x | verts = verts[-nrow(verts),] |
| 158 | } | |
| 159 | 137x | hole_mat = single_feature[!exterior_points,] |
| 160 | 137x | if(nrow(hole_mat) > 0) { |
| 161 | ! | holes = split(as.data.frame(hole_mat)[,c("X","Y")], |
| 162 | ! | hole_mat[,c("L1")]) |
| 163 | } else { | |
| 164 | 137x | holes = list() |
| 165 | } | |
| 166 | #Fix orientations | |
| 167 | 137x | if(!is_ccw_polygon(verts)) { |
| 168 | 137x | verts = verts[rev(seq_len(nrow(verts))),] |
| 169 | } | |
| 170 | 137x | vert_hashes = apply(verts,1,digest::digest) |
| 171 | 137x | cleaned_holes = list() |
| 172 | 137x | cntr = 1 |
| 173 | 137x | for(k in seq_len(length(holes))) { |
| 174 | ! | if(!is_simple_polygon(as.matrix(holes[[k]]))) { |
| 175 | ! | warning(sprintf("Hole in row %i in `sf` object not simple polygon, skipping", i)) |
| 176 | ! | next |
| 177 | } | |
| 178 | ! | if(is_ccw_polygon(holes[[k]])) { |
| 179 | ! | holes[[k]] = holes[[k]][rev(seq_len(nrow(holes[[k]]))),] |
| 180 | } | |
| 181 | ! | hole_hashes = apply(holes,1,digest::digest) |
| 182 | ! | if(any(hole_hashes %in% vert_hashes)) { |
| 183 | ! | warning(sprintf("Hole has shared node with vertex exterior which can cause problems with CGAL's underlying straight skeleton algorithm--skipping hole.")) |
| 184 | ! | next |
| 185 | } | |
| 186 | ! | cleaned_holes[[cntr]] = as.matrix(holes[[k]]) |
| 187 | ! | cntr = cntr + 1 |
| 188 | } | |
| 189 | #Skeletonize | |
| 190 | 137x | ss_list[[counter]] = skeletonize(as.matrix(verts), debug = debug, |
| 191 | 137x | holes = cleaned_holes, |
| 192 | 137x | return_raw_ss = return_raw_ss, |
| 193 | 137x | merge_nodes_tolerance = merge_nodes_tolerance) |
| 194 | 137x | attr(ss_list[[counter]], "original_sf_row_index") = list_idx[[i]] |
| 195 | 137x | counter = counter + 1 |
| 196 | } | |
| 197 | } | |
| 198 | } | |
| 199 | } | |
| 200 | 5x | if(length(ss_list) > 1) { |
| 201 | 4x | class(ss_list) = c("rayskeleton_list", "list") |
| 202 | 4x | return(ss_list) |
| 203 | } else { | |
| 204 | 1x | return(ss_list[[1]]) |
| 205 | } | |
| 206 | } else { | |
| 207 | #Fix orientations | |
| 208 | 139x | if(all(vertices[1,] == vertices[nrow(vertices),])) { |
| 209 | 1x | vertices = vertices[-nrow(vertices),] |
| 210 | } | |
| 211 | 139x | if(!is_ccw_polygon(as.matrix(vertices))) { |
| 212 | ! | vertices = vertices[rev(seq_len(nrow(vertices))),] |
| 213 | } | |
| 214 | 139x | for(k in seq_len(length(holes))) { |
| 215 | 2x | if(all(holes[[k]][1,] == holes[[k]][nrow(holes[[k]]),])) { |
| 216 | 2x | holes[[k]] = holes[[k]][-nrow(holes[[k]]),] |
| 217 | } | |
| 218 | 2x | holes[[k]] = as.matrix(holes[[k]]) |
| 219 | 2x | if(!is_simple_polygon(as.matrix(holes[[k]]))) { |
| 220 | ! | warning(sprintf("Hole in row %i in `sf` object not simple polygon, skipping", i)) |
| 221 | ! | next |
| 222 | } | |
| 223 | 2x | if(is_ccw_polygon(holes[[k]])) { |
| 224 | ! | holes[[k]] = holes[[k]][rev(seq_len(nrow(holes[[k]]))),] |
| 225 | } | |
| 226 | } | |
| 227 | } | |
| 228 | 139x | stopifnot(ncol(vertices) == 2) |
| 229 | 139x | if(all(vertices[1,] == vertices[nrow(vertices),])) { |
| 230 | ! | vertices = vertices[-nrow(vertices),] |
| 231 | } | |
| 232 | 139x | for(i in seq_len(length(holes))) { |
| 233 | 2x | hole = as.matrix(holes[[i]]) |
| 234 | 2x | if(all(hole[1,] == hole[nrow(hole),])) { |
| 235 | ! | holes[[i]] = hole[-nrow(hole),] |
| 236 | } else { | |
| 237 | 2x | holes[[i]] = hole |
| 238 | } | |
| 239 | } | |
| 240 | 139x | return_data = skeletonize_rcpp(vertices, holes, 0) |
| 241 | ||
| 242 | 139x | if(length(return_data) == 0) { |
| 243 | ! | warning("Polygon is not simple--not computing straight skeleton.") |
| 244 | ! | return() |
| 245 | } | |
| 246 | 139x | ss = do.call("rbind", return_data$bisectors) |
| 247 | 139x | colnames(ss) = c("end_x","end_y","start_x","start_y","time","time_start", "id", "id_start") |
| 248 | 139x | if(return_raw_ss) { |
| 249 | ! | return(as.data.frame(ss)) |
| 250 | } | |
| 251 | #De-duplicate half edges | |
| 252 | 139x | ss = ss[ss[,"id_start"] < ss[,"id"] | (ss[,"time"] == 0 & ss[,"time_start"] == 0) ,] |
| 253 | #Re-connect first vertex so everything is CCW | |
| 254 | # stopifnot(ss[1:2,"id_start"] == 0) | |
| 255 | # ss[1,] = ss[1,c(3,4,1,2,5,6,8,7)] | |
| 256 | 139x | ss = unique(as.data.frame(ss)) |
| 257 | 139x | ss$edge = ss$time == 0 & ss$time_start == 0 |
| 258 | # ss = ss[,c(1:8,9)] | |
| 259 | 139x | start_nodes = as.data.frame(ss[,c("id_start", "start_x", "start_y", "time_start")]) |
| 260 | 139x | start_nodes = arrange_base(unique(start_nodes[start_nodes$time_start == 0,]),"id_start") |
| 261 | 139x | ss = arrange_base(as.data.frame(ss), "time_start", "time") |
| 262 | 139x | start_ss = ss[,c(8,3:4,6,5)] |
| 263 | 139x | colnames(start_ss) = c("id","x","y","time","other_time") |
| 264 | 139x | end_ss = ss[,c(7,1:2,5,6)] |
| 265 | 139x | colnames(end_ss) = c("id","x","y","time","other_time") |
| 266 | 139x | nodes = rbind(start_ss,end_ss) |
| 267 | 139x | nodes$edge = nodes$time == 0 & nodes$other_time == 0 |
| 268 | 139x | rev_nodes = (nodes[nodes$time < nodes$other_time,]) |
| 269 | 139x | nodes = (nodes[nodes$time >= nodes$other_time,]) |
| 270 | 139x | if(any(!rev_nodes$id %in% nodes$id)) { |
| 271 | ! | cut_nodes = unique(rev_nodes$id[which(!rev_nodes$id %in% nodes$id)]) |
| 272 | ! | new_nodes = rev_nodes[rev_nodes$id %in% cut_nodes,] |
| 273 | ! | nodes = rbind(nodes,new_nodes) |
| 274 | } | |
| 275 | ||
| 276 | 139x | nodes = unique(nodes[,c(1:4,6)]) |
| 277 | 139x | nodes = arrange_base(nodes, "id") |
| 278 | 139x | links = ss[,c("id_start", "id", "time","time_start")] |
| 279 | 139x | colnames(links) = c("source","destination" ,"destination_time","source_time") |
| 280 | 139x | links = links[,c(1,2,4,3)] |
| 281 | 139x | links = as.data.frame(links) |
| 282 | 139x | links$edge = links$source_time == 0 & links$destination_time == 0 |
| 283 | 139x | links = links[,c(1,2,5,3,4)] |
| 284 | 139x | id_as_factor = as.factor(nodes$id) |
| 285 | 139x | id_levels = levels(id_as_factor) |
| 286 | 139x | nodes$id = as.factor(nodes$id) |
| 287 | 139x | links$source = as.integer(factor(links$source, levels = id_levels)) |
| 288 | 139x | links$destination = as.integer(factor(links$destination, levels = id_levels)) |
| 289 | 139x | nodes$id = as.integer(id_as_factor) |
| 290 | 139x | edge_links = links[links$edge,] |
| 291 | 139x | edge_links = edge_links[rev(seq_len(nrow(edge_links))),c(2,1,3,5,4)] |
| 292 | 139x | colnames(edge_links) = c("source","destination" ,"edge", "source_time","destination_time") |
| 293 | 139x | links = rbind(edge_links, links[!links$edge,]) |
| 294 | 139x | rownames(nodes) = seq_len(nrow(nodes)) |
| 295 | 139x | rownames(links) = seq_len(nrow(links)) |
| 296 | ||
| 297 | 139x | ss = list(nodes = nodes, links = links) |
| 298 | 139x | class(ss) = "rayskeleton" |
| 299 | 139x | for(i in seq_len(length(holes))) { |
| 300 | 2x | colnames(holes[[i]]) = c("x","y") |
| 301 | } | |
| 302 | 139x | colnames(vertices) = c("x","y") |
| 303 | 139x | attr(ss,"original_vertices") = vertices |
| 304 | 139x | attr(ss,"original_holes") = holes |
| 305 | 139x | if(merge_nodes_tolerance > 0) { |
| 306 | 139x | ss = discretize_and_merge_nodes(ss, merge_nodes_tolerance) |
| 307 | } | |
| 308 | 139x | ss = remove_reversed_links(ss) |
| 309 | 139x | return(ss) |
| 310 | } | |
| 311 |
| 1 | #' Extrude Sides of Polygon | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | extrude_sides = function(vertices, holes = list(), bottom = 0, top = 1) { | |
| 5 | 57x | vert_list = list() |
| 6 | 57x | idx_list = list() |
| 7 | #Need to ensure all polygons are closed | |
| 8 | 57x | close_poly = function(dat) { |
| 9 | 169x | if(!all(dat[1L,] == dat[nrow(dat),])) { |
| 10 | 169x | dat[c(seq_len(nrow(dat)), 1L),] |
| 11 | ! | } else dat |
| 12 | } | |
| 13 | 57x | vertices = close_poly(vertices) |
| 14 | 57x | holes = lapply(holes, close_poly) |
| 15 | ||
| 16 | 57x | all_polys = c(list(vertices), holes) |
| 17 | 57x | n_verts = 0 |
| 18 | 57x | for(j in seq_len(length(all_polys))) { |
| 19 | 169x | polyv = all_polys[[j]] |
| 20 | 169x | x = polyv[,1] |
| 21 | 169x | y = polyv[,2] |
| 22 | ||
| 23 | 169x | nr = nrow(polyv)-1 |
| 24 | ||
| 25 | 169x | vertices_top = cbind(polyv[-(nr+1),1:2],rep(top,nr)) |
| 26 | 169x | vertices_bottom = cbind(polyv[-(nr+1),1:2],rep(bottom,nr)) |
| 27 | 169x | colnames(vertices_top) = c("x","y","z") |
| 28 | 169x | colnames(vertices_bottom) = c("x","y","z") |
| 29 | ||
| 30 | 169x | vert_list[[j]] = rbind(vertices_top,vertices_bottom) |
| 31 | ||
| 32 | # Find which direction polygon is wound by computing signed area, | |
| 33 | # assumes non-intersecting polygon (side is a closed polygon). CW | |
| 34 | # outer polygon need to flip sides, as do CCW holes | |
| 35 | ||
| 36 | 169x | i = seq_len(nr) |
| 37 | 169x | ii = seq_len(nr) + 1L # i + 1 |
| 38 | 169x | area_s = sum(x[i] * y[ii] - x[ii] * y[i]) / 2 |
| 39 | ||
| 40 | 169x | ccw = area_s >= 0 # treat degenerates as counter-clockwise |
| 41 | 169x | side_rev = (j == 1L && ccw) || !ccw |
| 42 | #Get matrices to create triangles from polygon | |
| 43 | 169x | idx_mat = matrix(unlist(lapply(seq_len(nr),rep,2)), ncol = 3, nrow=2*nr) |
| 44 | 169x | tri_idx_mat = matrix(c(0,nr,nr, |
| 45 | 169x | 0,nr,0), nrow = 2*nr, ncol = 3, byrow=TRUE) |
| 46 | 169x | vert_idx_mat = matrix(c(0,0,1, |
| 47 | 169x | 0,1,1), nrow = 2*nr, ncol = 3, byrow=TRUE) |
| 48 | 169x | end_idx_mat = matrix(0, nrow = 2*nr, ncol = 3, byrow=TRUE) |
| 49 | 169x | end_idx_mat[seq(2*nr-1,2*nr,by=1),] = c(0,0,0,-nr,-nr,-nr) |
| 50 | 169x | tri_idx = idx_mat + tri_idx_mat + vert_idx_mat + end_idx_mat |
| 51 | 169x | if(!side_rev) { |
| 52 | ! | idx_list[[j]] = tri_idx[,3:1] + n_verts |
| 53 | } else { | |
| 54 | 169x | idx_list[[j]] = tri_idx + n_verts |
| 55 | } | |
| 56 | 169x | n_verts = n_verts + nrow(vert_list[[j]]) |
| 57 | } | |
| 58 | ||
| 59 | 57x | v_mat = do.call(rbind,vert_list) |
| 60 | 57x | i_mat = do.call(rbind,idx_list) |
| 61 | 57x | edge_mesh = rayvertex::construct_mesh(vertices = as.matrix(v_mat), |
| 62 | 57x | indices = as.matrix(i_mat)-1) |
| 63 | 57x | return(edge_mesh) |
| 64 | } |
| 1 | #' Recalculate Ordered IDs | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | recalculate_ordered_ids = function(skeleton) { | |
| 5 | 203x | nodes = skeleton$nodes |
| 6 | 203x | links = skeleton$links |
| 7 | 203x | id_as_factor = as.factor(nodes$id) |
| 8 | 203x | id_levels = levels(id_as_factor) |
| 9 | 203x | nodes$id = as.factor(nodes$id) |
| 10 | 203x | links$source = as.integer(factor(links$source, levels = id_levels)) |
| 11 | 203x | links$destination = as.integer(factor(links$destination, levels = id_levels)) |
| 12 | 203x | nodes$id = as.integer(id_as_factor) |
| 13 | 203x | skeleton$nodes = nodes |
| 14 | 203x | skeleton$links = links |
| 15 | 203x | return(skeleton) |
| 16 | } |
| 1 | #' Generate Offset Polygon | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | generate_offset_links_nodes = function(ss, offsets, return_polys = FALSE, progress = FALSE, verbose = FALSE) { | |
| 5 | 139x | links = ss$links |
| 6 | 139x | nodes = ss$nodes |
| 7 | 139x | offsets = offsets[which(offsets < max(nodes$time)) ] |
| 8 | ||
| 9 | 139x | node_maxima_ids = identify_maxima_nodes(ss) |
| 10 | 139x | nodes$local_maxima = nodes$id %in% node_maxima_ids |
| 11 | 139x | links$local_maxima_destination = links$destination %in% node_maxima_ids |
| 12 | 139x | links$local_maxima_source = links$source %in% node_maxima_ids |
| 13 | ||
| 14 | 139x | max_time = max(links$destination_time) |
| 15 | 139x | if(all(offsets >= max_time)) { |
| 16 | 19x | return(list(data.frame(x=numeric(),y=numeric()))) |
| 17 | } | |
| 18 | 120x | poly_list = generate_offset_links_nodes_rcpp(links, nodes, offsets = offsets, progress = progress) |
| 19 | ||
| 20 | 120x | new_links_offset = list() |
| 21 | 120x | for(ii in seq_along(poly_list)) { |
| 22 | 376x | if(length(poly_list[[ii]]) > 0) { |
| 23 | 376x | all_new_nodes = do.call("rbind",poly_list[[ii]]) |
| 24 | 376x | colnames(all_new_nodes) = c("polygon_id", "source", "destination", "new_id", |
| 25 | 376x | "x","y","time","x1","y1","x2","y2", "new_node") |
| 26 | 376x | if(return_polys) { |
| 27 | 56x | just_poly = all_new_nodes[,c("polygon_id", "x","y")] |
| 28 | 56x | names(just_poly) = c("id","x","y") |
| 29 | 56x | just_poly = split(as.data.frame(just_poly[,-1]), just_poly[,1]) |
| 30 | 56x | return(just_poly) |
| 31 | } | |
| 32 | 320x | new_links_poly = split(as.data.frame(all_new_nodes[,-1,drop=FALSE]), all_new_nodes[,1,drop=FALSE]) |
| 33 | ||
| 34 | 320x | new_links_offset[[ii]] = new_links_poly |
| 35 | } | |
| 36 | } | |
| 37 | 64x | if(return_polys) { |
| 38 | ! | all_new_nodes = do.call("rbind",new_links_offset) |
| 39 | ! | just_poly = all_new_nodes[,c("polygon_id", "x","y")] |
| 40 | ! | names(just_poly) = c("id","x","y") |
| 41 | ! | just_poly = split(as.data.frame(just_poly[,-1]), just_poly[,1]) |
| 42 | ! | return(just_poly) |
| 43 | } | |
| 44 | 64x | print_time(verbose, "Inserting polygon links and nodes") |
| 45 | ||
| 46 | 64x | return(insert_polygon_links_nodes(ss, new_links_offset)) |
| 47 | } | |
| 48 | ||
| 49 | ||
| 50 | #' Insert Polygon Links/Nodes | |
| 51 | #' | |
| 52 | #' @keywords internal | |
| 53 | insert_polygon_links_nodes = function(ss, new_links_all) { | |
| 54 | 64x | links = ss$links |
| 55 | 64x | nodes = ss$nodes |
| 56 | 64x | counter = 1 |
| 57 | 64x | poly_counter = 1 |
| 58 | 64x | new_link_list = list() |
| 59 | 64x | new_link_list_poly = list() |
| 60 | 64x | new_node_list = list() |
| 61 | 64x | links_to_remove = list() |
| 62 | 64x | raw_df = function(list_vals) { |
| 63 | 5248x | structure(list_vals, |
| 64 | 5248x | class = "data.frame", |
| 65 | 5248x | row.names = seq_len(length(list_vals[[1]]))) |
| 66 | } | |
| 67 | # plot_skeleton(ss, label_ids = TRUE) | |
| 68 | 64x | for(ii in seq_len(length(new_links_all))) { |
| 69 | 320x | new_links = new_links_all[[ii]] |
| 70 | 320x | if(length(new_links) == 0) { |
| 71 | ! | next |
| 72 | } | |
| 73 | 320x | new_nodes_single = do.call("rbind", new_links)[,c(3:6)] |
| 74 | # new_nodes_single = do.call("rbind", new_links)[,c(3:6,12)] | |
| 75 | # new_nodes_single = new_nodes_single[new_nodes_single$new_node == 1,1:4, drop = FALSE] | |
| 76 | 320x | colnames(new_nodes_single)[1] = "id" |
| 77 | 320x | new_nodes_single$edge = FALSE |
| 78 | 320x | new_node_list[[ii]] = new_nodes_single[order(new_nodes_single$id),] |
| 79 | 320x | for(i in seq_len(length(new_links))) { |
| 80 | 576x | single_poly = new_links[[i]] |
| 81 | 576x | prev_id = 0 |
| 82 | 576x | for(j in seq_len(nrow(single_poly))) { |
| 83 | 2816x | new_id = single_poly$new_id[j] |
| 84 | 2816x | new_time = single_poly$time[j] |
| 85 | 2816x | old_source = single_poly$source[j] |
| 86 | 2816x | old_destination = single_poly$destination[j] |
| 87 | 2816x | if(j != nrow(single_poly)) { |
| 88 | 2240x | poly_id = single_poly$new_id[j + 1] |
| 89 | } else { | |
| 90 | 576x | poly_id = single_poly$new_id[1] |
| 91 | } | |
| 92 | 2816x | link_remove_idx = which((links$source == old_source & |
| 93 | 2816x | links$destination == old_destination) | |
| 94 | 2816x | (links$destination == old_source & |
| 95 | 2816x | links$source == old_destination)) |
| 96 | 2816x | stopifnot(length(link_remove_idx) == 1) |
| 97 | 2816x | stopifnot(length(old_source) == 1) |
| 98 | 2816x | stopifnot(length(old_destination) == 1) |
| 99 | 2816x | stopifnot(length(poly_id) == 1) |
| 100 | 2816x | stopifnot(length(new_time) == 1) |
| 101 | ||
| 102 | 2816x | old_link = links[link_remove_idx,] |
| 103 | 2816x | old_source_time = old_link$source_time |
| 104 | 2816x | old_destination_time = old_link$destination_time |
| 105 | ||
| 106 | 2816x | if(old_source != new_id) { |
| 107 | 2432x | links_to_remove[[counter]] = link_remove_idx |
| 108 | ||
| 109 | 2432x | new_link_list[[counter]] = raw_df(list(source = c(old_source,new_id), |
| 110 | 2432x | destination = c(new_id,old_destination), |
| 111 | 2432x | source_time = c(old_source_time, new_time), |
| 112 | 2432x | destination_time = c(new_time, old_destination_time), |
| 113 | 2432x | edge = c(FALSE, FALSE), |
| 114 | 2432x | link_remove = rep(link_remove_idx,2), |
| 115 | 2432x | old_source_id = rep(old_source,2), |
| 116 | 2432x | old_dest_id = rep(old_destination,2))) #We will remove this variable before joining |
| 117 | 2432x | counter = counter + 1 |
| 118 | } | |
| 119 | # if(prev_id == 0 || prev_id == new_id ) { | |
| 120 | 2816x | new_link_list_poly[[poly_counter]] = raw_df(list(source = new_id, |
| 121 | 2816x | destination = poly_id, |
| 122 | 2816x | source_time = new_time, |
| 123 | 2816x | destination_time = new_time, |
| 124 | 2816x | edge = FALSE)) |
| 125 | 2816x | poly_counter = poly_counter + 1 |
| 126 | ||
| 127 | # } else { | |
| 128 | # new_link_list_poly[[poly_counter]] = data.frame(source = prev_id, | |
| 129 | # destination = new_id, | |
| 130 | # source_time = new_time, | |
| 131 | # destination_time = new_time, | |
| 132 | # edge = FALSE) | |
| 133 | # poly_counter = poly_counter + 1 | |
| 134 | # | |
| 135 | # new_link_list_poly[[poly_counter]] = data.frame(source = new_id, | |
| 136 | # destination = poly_id, | |
| 137 | # source_time = new_time, | |
| 138 | # destination_time = new_time, | |
| 139 | # edge = FALSE) | |
| 140 | # poly_counter = poly_counter + 1 | |
| 141 | ||
| 142 | # } | |
| 143 | # prev_id = poly_id | |
| 144 | # if(j == nrow(single_poly) && poly_id != single_poly$new_id[1]) { | |
| 145 | # browser() | |
| 146 | # new_link_list_poly[[poly_counter]] = data.frame(source = poly_id, | |
| 147 | # destination = single_poly$new_id[1], | |
| 148 | # source_time = new_time, | |
| 149 | # destination_time = new_time, | |
| 150 | # edge = FALSE) | |
| 151 | # poly_counter = poly_counter + 1 | |
| 152 | # } | |
| 153 | } | |
| 154 | } | |
| 155 | } | |
| 156 | 64x | new_nodes = do.call("rbind", new_node_list) |
| 157 | 64x | new_skeleton_links_raw = do.call("rbind",new_link_list) |
| 158 | 64x | links_to_slice = split(new_skeleton_links_raw,new_skeleton_links_raw[,6]) |
| 159 | # browser() | |
| 160 | 64x | new_links = lapply(links_to_slice, process_sliced_links) |
| 161 | 64x | new_skeleton_links = do.call("rbind",new_links) |
| 162 | 64x | new_poly_links = do.call("rbind", new_link_list_poly) |
| 163 | 64x | links = rbind(links[-unlist(links_to_remove),], |
| 164 | 64x | new_skeleton_links, |
| 165 | 64x | new_poly_links) |
| 166 | 64x | nodes_updated = rbind(nodes,new_nodes) |
| 167 | 64x | rownames(nodes_updated) = NULL |
| 168 | 64x | new_ss = list(nodes = nodes_updated, links = links) |
| 169 | 64x | class(new_ss) = "rayskeleton" |
| 170 | 64x | attr(new_ss, "original_vertices") = attr(ss, "original_vertices") |
| 171 | 64x | attr(new_ss, "original_holes") = attr(ss, "original_holes") |
| 172 | 64x | new_ss_no_dupe = remove_node_duplicates(new_ss) |
| 173 | 64x | return(new_ss_no_dupe) |
| 174 | } | |
| 175 | ||
| 176 | #' Process sliced links | |
| 177 | #' | |
| 178 | #' @keywords internal | |
| 179 | process_sliced_links = function(link_group) { | |
| 180 | 1152x | n_new_nodes = nrow(link_group)/2 |
| 181 | 1152x | new_link_info = link_group[seq(2,nrow(link_group),by=2),] |
| 182 | 1152x | old_source_time = link_group$source_time[1] |
| 183 | 1152x | old_dest_time = link_group$destination_time[2] |
| 184 | 1152x | if(old_source_time < old_dest_time) { |
| 185 | 1152x | start_node = link_group$old_source_id[1] |
| 186 | 1152x | end_node = link_group$old_dest_id[1] |
| 187 | 1152x | prev_time = old_source_time |
| 188 | 1152x | end_time = old_dest_time |
| 189 | } else { | |
| 190 | ! | end_node = link_group$old_source_id[1] |
| 191 | ! | start_node = link_group$old_dest_id[1] |
| 192 | ! | prev_time = old_dest_time |
| 193 | ! | end_time = old_source_time |
| 194 | ||
| 195 | } | |
| 196 | 1152x | new_links = list() |
| 197 | 1152x | current_node = start_node |
| 198 | 1152x | for(k in seq_len(n_new_nodes)) { |
| 199 | 2432x | new_node = new_link_info$source[k] |
| 200 | 2432x | new_time = new_link_info$source_time[k] |
| 201 | 2432x | if(new_time < prev_time) { |
| 202 | ! | stop(sprintf("New time (%f) is not greater than previous time (%f) ",new_time,prev_time)) |
| 203 | } | |
| 204 | 2432x | if(new_time != prev_time) { |
| 205 | 2432x | new_links[[k]] = data.frame(source = current_node, |
| 206 | 2432x | destination = new_node, |
| 207 | 2432x | source_time = prev_time, |
| 208 | 2432x | destination_time = new_time, |
| 209 | 2432x | edge = FALSE) |
| 210 | } | |
| 211 | 2432x | current_node = new_node |
| 212 | 2432x | prev_time = new_time |
| 213 | } | |
| 214 | 1152x | new_links[[k+1]] = data.frame(source = current_node, |
| 215 | 1152x | destination = end_node, |
| 216 | 1152x | source_time = prev_time, |
| 217 | 1152x | destination_time = end_time, |
| 218 | 1152x | edge = FALSE) |
| 219 | ||
| 220 | 1152x | return(do.call("rbind",new_links)) |
| 221 | } | |
| 222 | ||
| 223 | #' Make incremental nodes | |
| 224 | #' | |
| 225 | #' @keywords internal | |
| 226 | make_incremental_nodes = function(ss) { | |
| 227 | 64x | fac_id = factor(ss$nodes$id) |
| 228 | 64x | levels_id = levels(factor(ss$nodes$id)) |
| 229 | 64x | ss$nodes$id = as.integer(fac_id) |
| 230 | 64x | ss$links$source = as.integer(factor(ss$links$source, levels = levels_id)) |
| 231 | 64x | ss$links$destination = as.integer(factor(ss$links$destination, levels = levels_id)) |
| 232 | 64x | return(ss) |
| 233 | } |
| 1 | #' Generate 2D Bevel Profile for 3D Polygons | |
| 2 | #' | |
| 3 | #' @param bevel_type Character `angled`. Type of the bevel, one of the following options: | |
| 4 | #' - "circular": Creates a rounded bevel resembling a quarter-circle. | |
| 5 | #' - "exp": Creates an exponential curve, starting slow and accelerating. | |
| 6 | #' - "bump": Creates a bump-like profile, rising and falling within the coverage. | |
| 7 | #' - "step": Generates a step-like bevel with a flat top. | |
| 8 | #' - "block": Generates a block-like bevel, jumping straight to the max_height and back to the base. | |
| 9 | #' - "angled": Generates a straight angled bevel. You can optionally set the 'angle' parameter for this bevel. | |
| 10 | #' - "flat": Generates a flat area. | |
| 11 | #' @param bevel_start Default `0`. The starting point of the bevel along the curve, ranges between 0 and 1. | |
| 12 | #' @param bevel_end Default `0.2`. The ending point of the bevel along the curve, ranges between 0 and 1. | |
| 13 | #' @param max_height Default `1`. The maximum height of the bevel, as measured from the initial height. | |
| 14 | #' @param angle Default `NULL`. Optional angle parameter in degrees for angular bevels. | |
| 15 | #' @param curve_points Default `50`. Number of points to plot for curve-based bevels. | |
| 16 | #' @param reverse Default `FALSE`. If `TRUE`, the curve is reversed vertically. | |
| 17 | #' @param flip Default `FALSE`. If `TRUE`, the curve is flipped horizontally. | |
| 18 | #' @param initial_height Default `0`. The initial height from which the bevel starts. The bevel is rescaled to fit within the range from initial_height to max_height. | |
| 19 | #' @param manual_offsets Default `NULL`, none. This will force the bevel to add a point (interpolating between the two nearest points) | |
| 20 | #' at the specified offsets. This is useful when you want to add points at specific distances along the curve. | |
| 21 | #' @param add_end_points Default `TRUE`. Whether to ensure there is a point at zero and a point at one. | |
| 22 | #' @param step_epsilon Default `1e-5`. The size for the small percentage step when using a step bevel. | |
| 23 | #' @param set_minimum_zero Default `TRUE`. Whether to offset the lowest point of the bevel so it's at zero. | |
| 24 | #' @param zero_offset_epsilon Default `1e-5`. Amount to offset the bevel to ensure no self-intersection with the base. | |
| 25 | #' @param plot_bevel Default `FALSE`. Whether to plot the bevel. | |
| 26 | #' | |
| 27 | #' @return List containing 'x' and 'y', which are the coordinates of the 2D bevel profile. | |
| 28 | #' | |
| 29 | #' @export | |
| 30 | #' @examples | |
| 31 | #' # Generate a single bevel profile and plot it | |
| 32 | #' coords = generate_bevel("circular", 0.2, 0.8, 0.2, plot_bevel = TRUE) | |
| 33 | #' | |
| 34 | #' # Plot all bevel profiles in a grid | |
| 35 | #' plot_all_bevels = function() { | |
| 36 | #' oldpar = par(mfrow = c(4, 3), mai = c(0.2, 0.2, 0.5, 0.2)) | |
| 37 | #' on.exit(par(oldpar)) | |
| 38 | #' max_height = c(1,1,1,1) | |
| 39 | #' types = rep(c("circular", "exp", "bump", "step", "block", "angled"),2) | |
| 40 | #' reverses = c(rep(FALSE,6),rep(TRUE,6)) | |
| 41 | #' for(i in seq_len(length(types))) { | |
| 42 | #' coords = generate_bevel(types[i], 0.2, 0.8, 1, flip = TRUE, | |
| 43 | #' angle = 45, reverse = reverses[i], plot_bevel = TRUE) | |
| 44 | #' } | |
| 45 | #' } | |
| 46 | #' plot_all_bevels() | |
| 47 | generate_bevel = function(bevel_type = "angled", bevel_start = 0, bevel_end = 0.2, | |
| 48 | max_height = 1, angle = NULL, curve_points = 50, | |
| 49 | reverse = FALSE, flip = FALSE, | |
| 50 | initial_height = 0, add_end_points = TRUE, | |
| 51 | manual_offsets = NULL, | |
| 52 | step_epsilon = 1e-8, | |
| 53 | plot_bevel = FALSE, | |
| 54 | set_minimum_zero = TRUE, | |
| 55 | zero_offset_epsilon = 1e-5) { | |
| 56 | # Check angle constraint if bevel_type is angled | |
| 57 | ! | if(bevel_type == "angled") { |
| 58 | ! | if(!is.null(angle)) { |
| 59 | ! | stopifnot(angle < 90 && angle > -90) |
| 60 | ! | angle = angle*pi/180 |
| 61 | ! | max_height = tan(angle) * (bevel_end - bevel_start) |
| 62 | } | |
| 63 | } | |
| 64 | ||
| 65 | # Initialize empty vectors for x and y | |
| 66 | ! | x = c() |
| 67 | ! | y = c() |
| 68 | # Define curve points based on bevel_type | |
| 69 | ! | if(bevel_type == "step") { |
| 70 | ! | x = c(bevel_start, bevel_start + step_epsilon) |
| 71 | ! | y = c(0, max_height) |
| 72 | ! | } else if(bevel_type == "block") { |
| 73 | ! | x = c(bevel_start, bevel_start + step_epsilon, bevel_end - step_epsilon, bevel_end) |
| 74 | ! | y = c(0,max_height, max_height, 0) |
| 75 | ! | } else if(bevel_type == "angled") { |
| 76 | ! | x = c(bevel_start, bevel_end) |
| 77 | ! | y = c(0, max_height) |
| 78 | ! | } else if(bevel_type == "flat") { |
| 79 | ! | x = c(bevel_start, bevel_end) |
| 80 | ! | y = c(0, 0) |
| 81 | } else { | |
| 82 | ! | x_curve = seq(bevel_start, bevel_end, length.out = curve_points) |
| 83 | ! | if(bevel_type == "circular") { |
| 84 | ! | y_curve = sqrt(1 - ((x_curve - bevel_start) / (bevel_end - bevel_start) - 1)^2) |
| 85 | ! | } else if(bevel_type == "exp") { |
| 86 | ! | y_curve = 1 - exp(-5 * (x_curve - bevel_start) / (bevel_end - bevel_start)) |
| 87 | ! | } else if(bevel_type == "bump") { |
| 88 | ! | y_curve = sqrt(1 - (2 * (x_curve - bevel_start) / (bevel_end - bevel_start) - 1)^2) |
| 89 | } else { | |
| 90 | ! | stop(sprintf("bevel_type `%s` not recognized.", bevel_type)) |
| 91 | } | |
| 92 | ! | y_curve = y_curve * max_height |
| 93 | ! | x = c(x, x_curve) |
| 94 | ! | y = c(y, y_curve) |
| 95 | } | |
| 96 | ! | if(flip) { |
| 97 | ! | y = rev(y) |
| 98 | } | |
| 99 | ! | if(add_end_points) { |
| 100 | ! | if(x[1] != 0) { |
| 101 | ! | x = c(0,x) |
| 102 | ! | y = c(y[1],y) |
| 103 | } | |
| 104 | ! | if(x[length(x)] != 1) { |
| 105 | ! | x = c(x,1) |
| 106 | ! | last_val = y[length(y)] |
| 107 | ! | y = c(y,last_val) |
| 108 | } | |
| 109 | } | |
| 110 | ! | if(!is.null(manual_offsets)) { |
| 111 | ! | manual_offsets = manual_offsets[manual_offsets < 1 & manual_offsets > 0] |
| 112 | ! | for(j in seq_len(length(manual_offsets))) { |
| 113 | ! | if(any(abs(x-manual_offsets[j]) < 1e-14)) { |
| 114 | ! | manual_offsets[j] = NA |
| 115 | } | |
| 116 | } | |
| 117 | ! | manual_offsets = manual_offsets[!is.na(manual_offsets)] |
| 118 | ! | if(length(manual_offsets) > 0) { |
| 119 | ! | max_x = max(x) |
| 120 | ! | manual_vals = stats::approx(x=x,y=y, xout = manual_offsets)$y |
| 121 | ! | manual_vals[max_x < manual_offsets] = y[length(y)] |
| 122 | ! | x = c(x,manual_offsets) |
| 123 | ! | x_order = order(x) |
| 124 | ! | x = x[x_order] |
| 125 | ! | y = c(y,manual_vals) |
| 126 | ! | y = y[x_order] |
| 127 | } | |
| 128 | } | |
| 129 | # Reverse the bevel if specified | |
| 130 | ! | if(reverse) { |
| 131 | ! | y = max_height - y |
| 132 | } | |
| 133 | # Adjust heights based on initial_height | |
| 134 | ! | diff_height = y[1]-initial_height |
| 135 | ! | y = y - diff_height |
| 136 | ||
| 137 | ! | if(set_minimum_zero && min(y) <= 0) { |
| 138 | ! | y = y - min(y) + zero_offset_epsilon |
| 139 | } | |
| 140 | ||
| 141 | ! | if(plot_bevel) { |
| 142 | ! | plot(x, y, type = 'l', axes = FALSE, lwd = 2, xlim = c(min(x)-0.1, max(x)+0.1), ylim = c(min(y)-0.1, max(y)+0.1)) |
| 143 | ! | graphics::box() |
| 144 | } | |
| 145 | ||
| 146 | ! | return(list(x = x, y = y)) |
| 147 | } | |
| 148 | ||
| 149 | #' Generate Complex 2D Bevel Profile for 3D Polygons | |
| 150 | #' | |
| 151 | #' All arguments are recycled to the length of the longest argument, allowing for the generation of | |
| 152 | #' complex and repetitive bevel patterns without manual replication of argument values. | |
| 153 | #' | |
| 154 | #' @param bevel_type Vector of bevel types. Options are: `"circular"`, `"exp"`, `"bump"`, `"step"`, `"block"`, `"angled"`. | |
| 155 | #' Note that for the `"step"` type, the transition occurs at `bevel_start`. | |
| 156 | #' @param bevel_start Numeric vector of values between `0` and `1`. | |
| 157 | #' Percentage distance in the interior the polygon at which to begin the corresponding `bevel_type`. Note that for the `"step"` type, this is ignored. | |
| 158 | #' @param bevel_end Numeric vector of values between `0` and `1`. | |
| 159 | #' Percentage distance in the interior the polygon at which to end the corresponding `bevel_type`. | |
| 160 | #' @param segment_height Numeric vector. The maximum heights of each bevel, as measured from the initial height at the end of the previous bevel. | |
| 161 | #' @param angle Default `NULL`. Numeric vector. Optional angle parameter in degrees for angular bevels (overrides values in `max_height`). | |
| 162 | #' @param curve_points Default `50`. Integer vector of number of points for each curve. | |
| 163 | #' @param manual_offsets Default `NULL`, none. This will force the bevel to add a point (interpolating between the two nearest points) | |
| 164 | #' at the specified offsets. This is useful when you want to add points at specific distances along the curve. | |
| 165 | #' @param add_end_points Default `TRUE`. Whether to ensure there is a point at zero and a point at one. | |
| 166 | #' @param reverse Default `FALSE`. Whether to reverse each bevel. | |
| 167 | #' @param flip Default `FALSE`. Whether to reverse each bevel horizontally. | |
| 168 | #' @param plot_bevel Default `FALSE`. Whether to plot the resulting bevel. | |
| 169 | #' @param overall_height Default `NA`. Numeric value specifying the overall height of the curve. | |
| 170 | #' @param set_minimum_zero Default `TRUE`. Whether to offset the lowest point of the bevel so it's at zero. | |
| 171 | #' @param zero_offset_epsilon Default `1e-5`. Amount to offset the bevel to ensure no self-intersection with the base. | |
| 172 | #' | |
| 173 | #' @return List containing 'x' and 'y', which are the coordinates of the complex 2D bevel profile | |
| 174 | #' @export | |
| 175 | #' @examples | |
| 176 | #' # Generate a complex bevel profile and plot it | |
| 177 | #' complex_coords = generate_complex_bevel( | |
| 178 | #' bevel_type = c("circular", "bump", "step", "block", "angled"), | |
| 179 | #' bevel_start = c(0, 0.2, 0.6, 0.7, 0.9), | |
| 180 | #' bevel_end = c(0.2, 0.5, 0.7, 0.8, 1.0), | |
| 181 | #' segment_height = c(0.1, 0.2, 0.2, 0.2, 0.4), | |
| 182 | #' angle = 45, | |
| 183 | #' curve_points = c(50, 50, 50, 1, 1), | |
| 184 | #' reverse = c(FALSE, TRUE, FALSE, FALSE, FALSE), | |
| 185 | #' plot_bevel = TRUE | |
| 186 | #' ) | |
| 187 | #' # Create a step function with reverses to generate a square wave pattern | |
| 188 | #' complex_coords = generate_complex_bevel( | |
| 189 | #' bevel_type = "step", | |
| 190 | #' bevel_start = head(seq(0,1,by=0.05),-1), | |
| 191 | #' bevel_end = 1, | |
| 192 | #' segment_height = 0.1, | |
| 193 | #' angle = 45, | |
| 194 | #' reverse = c(FALSE, TRUE), | |
| 195 | #' plot_bevel = TRUE | |
| 196 | #' ) | |
| 197 | #' #Generate an increasing sawtooth pattern with angles | |
| 198 | #' complex_coords = generate_complex_bevel( | |
| 199 | #' bevel_type = "angled", | |
| 200 | #' bevel_start = head(seq(0,1,by=0.05),-1), | |
| 201 | #' bevel_end = tail(seq(0,1,by=0.05),-1), | |
| 202 | #' segment_height = 0.1, | |
| 203 | #' angle = c(45,30), | |
| 204 | #' reverse = c(FALSE, TRUE), | |
| 205 | #' plot_bevel = TRUE | |
| 206 | #' ) | |
| 207 | #' # Create a step function to turn polygons into a ziggurat (note bevel_end is ignored) | |
| 208 | #' complex_coords = generate_complex_bevel( | |
| 209 | #' bevel_type = "step", | |
| 210 | #' bevel_start = head(seq(0,1,by=0.05),-1), | |
| 211 | #' bevel_end = 1, | |
| 212 | #' segment_height = 0.1, | |
| 213 | #' reverse = FALSE, | |
| 214 | #' plot_bevel = TRUE | |
| 215 | #' ) | |
| 216 | generate_complex_bevel = function(bevel_type, | |
| 217 | bevel_start = 0, | |
| 218 | bevel_end = 1, | |
| 219 | segment_height = 1, | |
| 220 | angle = 45, | |
| 221 | curve_points = 30, | |
| 222 | reverse = FALSE, | |
| 223 | flip = FALSE, | |
| 224 | manual_offsets = NULL, | |
| 225 | add_end_points = TRUE, | |
| 226 | plot_bevel = FALSE, | |
| 227 | overall_height = NA, | |
| 228 | set_minimum_zero = TRUE, | |
| 229 | zero_offset_epsilon = 1e-6) { | |
| 230 | ! | completed_vals = data.frame(bevel_type = bevel_type, |
| 231 | ! | bevel_start = bevel_start, |
| 232 | ! | bevel_end = bevel_end, |
| 233 | ! | segment_height = segment_height, |
| 234 | ! | angle = angle, |
| 235 | ! | curve_points = curve_points, |
| 236 | ! | flip = flip, |
| 237 | ! | reverse = reverse) |
| 238 | # Sort by bevel_start for sequential generation | |
| 239 | ! | completed_vals = completed_vals[order(completed_vals$bevel_start), ] |
| 240 | ||
| 241 | # Add stop time to step types | |
| 242 | ! | for(i in seq_len(nrow(completed_vals))) { |
| 243 | ! | if(completed_vals[i,"bevel_type"] == "step") { |
| 244 | ! | completed_vals[i,"bevel_end"] = completed_vals[i,"bevel_start"] + 1e-5 |
| 245 | } | |
| 246 | } | |
| 247 | # Error if the bevels overlap | |
| 248 | ! | for(i in seq_len(nrow(completed_vals)-1)) { |
| 249 | ! | if(completed_vals[i,"bevel_end"] > completed_vals[i + 1,"bevel_start"]) { |
| 250 | ! | stop(sprintf("%ith `bevel_start` (%0.3f) starts before %ith `bevel_end` (%0.3f)", |
| 251 | ! | i+i, i, completed_vals[i + 1,"bevel_start"], completed_vals[i,"bevel_end"])) |
| 252 | } | |
| 253 | } | |
| 254 | ! | x = c() |
| 255 | ! | y = c() |
| 256 | ! | y_prev_end = 0 |
| 257 | ||
| 258 | ! | manual_offsets_bool = rep(FALSE, length(manual_offsets)) |
| 259 | ||
| 260 | ! | for(i in seq_len(nrow(completed_vals))) { |
| 261 | ! | row = completed_vals[i, ] |
| 262 | ! | manual_offsets_bool[manual_offsets >= row$bevel_start & |
| 263 | ! | manual_offsets <= row$bevel_end] = TRUE |
| 264 | ! | manual_offset_segment = manual_offsets[manual_offsets >= row$bevel_start & |
| 265 | ! | manual_offsets <= row$bevel_end] |
| 266 | ! | if(length(manual_offset_segment) == 0) { |
| 267 | ! | manual_offset_segment = NULL |
| 268 | } | |
| 269 | ! | bevel_segment = generate_bevel( |
| 270 | ! | bevel_type = row$bevel_type, |
| 271 | ! | bevel_start = row$bevel_start, |
| 272 | ! | bevel_end = row$bevel_end, |
| 273 | ! | max_height = row$segment_height, |
| 274 | ! | angle = if (!is.null(row$angle)) row$angle else NULL, |
| 275 | ! | curve_points = row$curve_points, |
| 276 | ! | reverse = row$reverse, |
| 277 | ! | flip = row$flip, |
| 278 | ! | manual_offsets = manual_offset_segment, |
| 279 | ! | initial_height = y_prev_end, # Pass the last height of the previous bevel as the initial height |
| 280 | ! | add_end_points = FALSE, |
| 281 | ! | set_minimum_zero = FALSE |
| 282 | ) | |
| 283 | ||
| 284 | ! | y_prev_end = bevel_segment$y[length(bevel_segment$y)] # Update y_prev_end for the next iteration |
| 285 | ||
| 286 | ! | if(i == 1) { |
| 287 | ! | x = bevel_segment$x |
| 288 | ! | y = bevel_segment$y |
| 289 | } else { | |
| 290 | ! | x = c(x, bevel_segment$x) |
| 291 | ! | y = c(y, bevel_segment$y) |
| 292 | } | |
| 293 | } | |
| 294 | ||
| 295 | ! | if(add_end_points) { |
| 296 | ! | if(x[1] != 0) { |
| 297 | ! | x = c(0,x) |
| 298 | ! | y = c(y[1],y) |
| 299 | } | |
| 300 | ! | if(x[length(x)] != 1) { |
| 301 | ! | x = c(x,1) |
| 302 | ! | y = c(y,y[length(y)]) |
| 303 | } | |
| 304 | } | |
| 305 | ||
| 306 | ! | duplicated_x = duplicated(x) |
| 307 | ! | x = x[!duplicated_x] |
| 308 | ! | y = y[!duplicated_x] |
| 309 | ||
| 310 | ! | if(any(manual_offsets_bool)) { |
| 311 | ! | manual_offsets_remaining = manual_offsets[!manual_offsets_bool] |
| 312 | ! | manual_heights_insert = stats::approx(x=x,y=y, xout = manual_offsets_remaining)$y |
| 313 | ! | x = c(x,manual_offsets_remaining) |
| 314 | ! | y = c(y,manual_heights_insert) |
| 315 | ! | order_x = order(x) |
| 316 | ! | x = x[order_x] |
| 317 | ! | y = y[order_x] |
| 318 | } | |
| 319 | ||
| 320 | ! | duplicated_x = duplicated(x) |
| 321 | ! | x = x[!duplicated_x] |
| 322 | ! | y = y[!duplicated_x] |
| 323 | ||
| 324 | ||
| 325 | ! | if(!is.na(overall_height)) { |
| 326 | ! | stopifnot(is.numeric(overall_height) && length(overall_height) == 1) |
| 327 | ! | min_val = min(y) |
| 328 | ! | max_val = max(y) |
| 329 | ! | y = (y - min_val) / (max_val - min_val) * overall_height + min_val |
| 330 | } | |
| 331 | ||
| 332 | ! | if(set_minimum_zero && min(y) <= 0) { |
| 333 | ! | range_y = range(y) |
| 334 | ! | range_y = range_y[2] - range_y[1] |
| 335 | ! | epsilon = range_y * zero_offset_epsilon |
| 336 | ! | y = y - min(y) + epsilon |
| 337 | } | |
| 338 | ||
| 339 | ! | if(plot_bevel) { |
| 340 | ! | plot(x, y, type = 'l', axes = FALSE, lwd = 2, xlim = c(min(x)-0.1, max(x)+0.1), ylim = c(min(y)-0.1, max(y)+0.1)) |
| 341 | ! | graphics::box() |
| 342 | } | |
| 343 | ||
| 344 | ! | return(list(x = x, y = y)) |
| 345 | } |
| 1 | #' Print time | |
| 2 | #' | |
| 3 | #' @return Nothing | |
| 4 | #' @keywords internal | |
| 5 | init_time = function() { | |
| 6 | 320x | assign("init_time", proc.time()[3], envir = ray_environment) |
| 7 | 320x | assign("prev_time", proc.time()[3], envir = ray_environment) |
| 8 | } | |
| 9 | ||
| 10 | #' Get time | |
| 11 | #' | |
| 12 | #' @return Nothing | |
| 13 | #' @keywords internal | |
| 14 | get_time = function(init = TRUE) { | |
| 15 | ! | if(init) { |
| 16 | ! | get("init_time", envir = ray_environment) |
| 17 | } else { | |
| 18 | ! | get("prev_time", envir = ray_environment) |
| 19 | } | |
| 20 | } | |
| 21 | ||
| 22 | #' Print time | |
| 23 | #' | |
| 24 | #' @return Nothing | |
| 25 | #' @keywords internal | |
| 26 | print_time = function(verbose = FALSE, message_text = "") { | |
| 27 | 385x | if(verbose) { |
| 28 | ! | time_now = proc.time()[3] |
| 29 | ! | message(sprintf("%-27s: %0.1f secs (Total: %0.1f secs)", |
| 30 | ! | message_text, |
| 31 | ! | time_now-get_time(FALSE), |
| 32 | ! | time_now-get_time(TRUE))) |
| 33 | ! | assign("prev_time", time_now, envir = ray_environment) |
| 34 | } | |
| 35 | } |
| 1 | #' Discretize and Merge Nodes | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | discretize_and_merge_nodes = function(skeleton, tolerance = 1e-5) { | |
| 5 | # Calculate bounding box of the nodes | |
| 6 | 139x | x_range = range(skeleton$nodes$x) |
| 7 | 139x | y_range = range(skeleton$nodes$y) |
| 8 | 139x | width = x_range[2] - x_range[1] |
| 9 | 139x | height = y_range[2] - y_range[1] |
| 10 | ||
| 11 | # Snap each point to its nearest grid cell | |
| 12 | 139x | skeleton$nodes$grid_x = round((skeleton$nodes$x - x_range[1]) / width * 1/tolerance) |
| 13 | 139x | skeleton$nodes$grid_y = round((skeleton$nodes$y - y_range[1]) / height * 1/tolerance) |
| 14 | ||
| 15 | # Merge nodes based on their grid cells | |
| 16 | 139x | skeleton$nodes$grid_id = paste(skeleton$nodes$grid_x, skeleton$nodes$grid_y, sep="-") |
| 17 | 139x | nodes_to_remove = duplicated(skeleton$nodes$grid_id) |
| 18 | 139x | nodes_to_keep = which(!nodes_to_remove) |
| 19 | ||
| 20 | # Map all nodes to their corresponding kept node | |
| 21 | 139x | id_map = stats::setNames(nodes_to_keep, skeleton$nodes$id[nodes_to_keep]) |
| 22 | 139x | for(node_id in skeleton$nodes$id) { |
| 23 | 14332x | grid_id = skeleton$nodes$grid_id[skeleton$nodes$id == node_id] |
| 24 | 14332x | id_map[as.character(node_id)] = skeleton$nodes$id[skeleton$nodes$grid_id == grid_id][1] |
| 25 | } | |
| 26 | ||
| 27 | # Update links to reflect the merged nodes | |
| 28 | 139x | skeleton$links$source = id_map[as.character(skeleton$links$source)] |
| 29 | 139x | skeleton$links$destination = id_map[as.character(skeleton$links$destination)] |
| 30 | ||
| 31 | # Remove duplicate nodes | |
| 32 | 139x | skeleton$nodes = skeleton$nodes[!nodes_to_remove, ] |
| 33 | 139x | skeleton$nodes = skeleton$nodes[, c("id", "x", "y", "time", "edge"), drop = FALSE] |
| 34 | ||
| 35 | # Calculate new ids | |
| 36 | 139x | skeleton = recalculate_ordered_ids(skeleton) |
| 37 | ||
| 38 | #Remove self-referencing links | |
| 39 | 139x | skeleton$links = skeleton$links[skeleton$links$source != skeleton$links$destination, ] |
| 40 | ||
| 41 | #Remove duplicate links | |
| 42 | 139x | link_duplicates = duplicated(skeleton$links[, c("source", "destination")]) |
| 43 | 139x | skeleton$links = skeleton$links[!link_duplicates, ] |
| 44 | ||
| 45 | 139x | return(skeleton) |
| 46 | } |
| 1 | #' Remove Node Duplicates | |
| 2 | #' | |
| 3 | #' @description Replace dup | |
| 4 | #' | |
| 5 | #' @param ss | |
| 6 | #' | |
| 7 | #' @keywords internal | |
| 8 | remove_node_duplicates = function(ss) { | |
| 9 | 64x | ss$nodes = ss$nodes[!duplicated(ss$nodes),] |
| 10 | #Calculate unique nodes (position/time) | |
| 11 | 64x | row_hashes = apply(ss$nodes[,c(-1,-4)], 1, digest::digest) |
| 12 | 64x | unique_row_hashes = unique(row_hashes) |
| 13 | 64x | id_val = rep(0, length(unique_row_hashes)) |
| 14 | 64x | replace_node_list = list() |
| 15 | ||
| 16 | #Find first row index that matches row hash | |
| 17 | 64x | for(i in seq_len(length(unique_row_hashes))) { |
| 18 | 3776x | tmp_id_val = which(unique_row_hashes[i] == row_hashes) |
| 19 | 3776x | id_val[i] = tmp_id_val[1] |
| 20 | 3776x | replace_node_list[[i]] = tmp_id_val[-1] |
| 21 | } | |
| 22 | #Copy original skeleton | |
| 23 | 64x | new_ss = ss |
| 24 | ||
| 25 | #Look through all new id values and replace links references to new IDs | |
| 26 | 64x | for(i in seq_len(length(id_val))) { |
| 27 | 3776x | if(length(replace_node_list[[i]]) > 0) { |
| 28 | #Replace link information with de-duplicated nodes | |
| 29 | ! | new_ss$links$source[ss$links$source %in% replace_node_list[[i]] ] = id_val[i] |
| 30 | ! | new_ss$links$destination[ss$links$destination %in% replace_node_list[[i]] ] = id_val[i] |
| 31 | } | |
| 32 | } | |
| 33 | 64x | new_ss$links = new_ss$links[!duplicated(new_ss$links),] |
| 34 | 64x | new_ss$links = new_ss$links[new_ss$links$source != new_ss$links$destination,] |
| 35 | ||
| 36 | 64x | new_ss$nodes = new_ss$nodes[!new_ss$nodes$id %in% unlist(replace_node_list),] |
| 37 | 64x | new_ss_inc = make_incremental_nodes(new_ss) |
| 38 | 64x | return(new_ss_inc) |
| 39 | } |
| 1 | #' Plot Offset Polygons | |
| 2 | #' | |
| 3 | #' Plot the offset polygons generated by the `generate_offset_polygon` function. | |
| 4 | #' | |
| 5 | #' @param offset_polygons Default `NULL`. A `rayskeleton_polygon` or `rayskeleton_polygon_list` object, generated from | |
| 6 | #' `generate_offset_polygon()`. | |
| 7 | #' @param color Default `grDevices::heat.colors`. A color or palette function to generate the color palette for the offset polygons' borders. | |
| 8 | #' @param xlim Default `NULL`. The x-axis limits as a vector of two values (min, max). If `NULL`, it calculates the limits from the data. | |
| 9 | #' @param ylim Default `NULL`. The y-axis limits as a vector of two values (min, max). If `NULL`, it calculates the limits from the data. | |
| 10 | #' @param fill Default `NULL`. A color or palette function to generate the fill palette for the polygons' interiors. | |
| 11 | #' @param linewidth Default `1`. The linewidth of the polygon. | |
| 12 | #' @param background Default `"white"`. Background color. | |
| 13 | #' @param plot_original_polygon Default `TRUE`. Whether to plot the original polygon. | |
| 14 | #' @param plot_skeleton Default `FALSE`. Whether to plot the straight skeleton. | |
| 15 | #' @param return_layers Default `FALSE`, plots the figure. If `TRUE`, this will instead | |
| 16 | #' return a list of the ggplot layers. | |
| 17 | #' @param ... Additional arguments to pass to `plot_skeleton()` if `plot_skeleton = TRUE` | |
| 18 | #' | |
| 19 | #' | |
| 20 | #' @return A plot showing the offset polygons. | |
| 21 | #' @export | |
| 22 | #' @examples | |
| 23 | #' # Outer polygon | |
| 24 | #' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE) | |
| 25 | #' # Holes inside the polygon | |
| 26 | #' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,] | |
| 27 | #' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,] | |
| 28 | #' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2)) | |
| 29 | #' if(run_docs_raybevel()) { | |
| 30 | #' plot_skeleton(skeleton) | |
| 31 | #' } | |
| 32 | #' | |
| 33 | #' #Generate three offsets with the skeleton | |
| 34 | #' if(run_docs_raybevel()) { | |
| 35 | #' plot_offset_polygon(generate_offset_polygon(skeleton, c(0.25,0.75,1.5,2)), plot_skeleton = TRUE) | |
| 36 | #' } | |
| 37 | #' | |
| 38 | #' #Generate many offsets | |
| 39 | #' if(run_docs_raybevel()) { | |
| 40 | #' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0.05,2.55,by=0.1))) | |
| 41 | #' } | |
| 42 | #' | |
| 43 | #' #Pass a palette | |
| 44 | #' if(run_docs_raybevel()) { | |
| 45 | #' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0.05,2.55,by=0.1)), | |
| 46 | #' color = heat.colors) | |
| 47 | #' } | |
| 48 | #' | |
| 49 | #' #Pass colors manually (colors in excess of the number of offsets are ignored) | |
| 50 | #' if(run_docs_raybevel()) { | |
| 51 | #' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0.05,2.55,by=0.1)), | |
| 52 | #' color = rep(c("red","red","blue","blue"),100)) | |
| 53 | #' } | |
| 54 | #' | |
| 55 | #' # Skeletonize and plot an {sf} object | |
| 56 | #' if(run_docs_raybevel()) { | |
| 57 | #' us_states = spData::us_states | |
| 58 | #' texas = us_states[us_states$NAME == "Texas",] | |
| 59 | #' texas_skeleton = skeletonize(texas) | |
| 60 | #' plot_offset_polygon(generate_offset_polygon(texas_skeleton, seq(0, 2.5, by = 0.1)), | |
| 61 | #' color = heat.colors, | |
| 62 | #' linewidth = 1) | |
| 63 | #' } | |
| 64 | plot_offset_polygon = function(offset_polygons, | |
| 65 | plot_original_polygon = TRUE, | |
| 66 | fill = NA, color= "dodgerblue", xlim=NULL, ylim=NULL, | |
| 67 | linewidth = 1, background = "white", | |
| 68 | plot_skeleton = FALSE, return_layers = FALSE, ...) { | |
| 69 | # Check if ggplot2 package is installed | |
| 70 | 5x | if(!(length(find.package("ggplot2", quiet = TRUE)) > 0)) { |
| 71 | ! | stop("{ggplot2} package required for plot_offset_polygon_ggplot()") |
| 72 | } | |
| 73 | ||
| 74 | # Import ggplot2 functions | |
| 75 | 5x | ggplot = ggplot2::ggplot |
| 76 | 5x | aes = ggplot2::aes |
| 77 | 5x | geom_polygon = ggplot2::geom_polygon |
| 78 | 5x | theme_void = ggplot2::theme_void |
| 79 | 5x | coord_fixed = ggplot2::coord_fixed |
| 80 | 5x | theme = ggplot2::theme |
| 81 | 5x | element_rect = ggplot2::element_rect |
| 82 | ||
| 83 | 5x | x = y = NULL |
| 84 | # Create an empty ggplot object | |
| 85 | ||
| 86 | 5x | p = list() |
| 87 | 5x | if (inherits(offset_polygons, "rayskeleton_polygons")) { |
| 88 | 4x | if(all(is.na(offset_polygons))) { |
| 89 | ! | stop("No non-NA offset polygons passed.") |
| 90 | } | |
| 91 | 4x | max_offsets = max(unlist(lapply(offset_polygons[!is.na(offset_polygons)], length))) |
| 92 | ||
| 93 | # Set color palettes if provided | |
| 94 | 4x | n_polygons = max_offsets |
| 95 | 4x | if(is.function(color)) { |
| 96 | ! | color = color(n_polygons) |
| 97 | 4x | } else if (is.character(color)) { |
| 98 | 4x | if(length(color) == 1) { |
| 99 | 4x | color = rep(color[1], n_polygons) |
| 100 | } | |
| 101 | } else { | |
| 102 | ! | color = rep(color[1], n_polygons) |
| 103 | } | |
| 104 | ||
| 105 | 4x | if(is.function(fill)) { |
| 106 | ! | fill = fill(n_polygons) |
| 107 | 4x | } else if (is.character(fill)) { |
| 108 | ! | if(length(fill) == 1) { |
| 109 | ! | fill = rep(fill[1], n_polygons) |
| 110 | } | |
| 111 | } else { | |
| 112 | 4x | fill = rep(fill[1], n_polygons) |
| 113 | } | |
| 114 | 4x | ray_environment$final_polygon = FALSE |
| 115 | 4x | on.exit({ray_environment$final_polygon = TRUE}, |
| 116 | 4x | add = TRUE) |
| 117 | 4x | for(ii in seq_len(length(offset_polygons))) { |
| 118 | 71x | single_skeleton = offset_polygons[[ii]] |
| 119 | 71x | number_offsets = attr(single_skeleton, "number_offsets") |
| 120 | 71x | for(j in seq_len(number_offsets)) { |
| 121 | 75x | single_offset = single_skeleton[[j]] |
| 122 | 75x | n_polygons = attr(single_offset, "number_polygons") |
| 123 | 75x | for(i in seq_len(n_polygons)) { |
| 124 | 88x | if(nrow(single_offset[[i]]) > 0) { |
| 125 | 69x | poly = single_offset[[i]] |
| 126 | 69x | colnames(poly) = c("x","y") |
| 127 | 69x | p[[length(p) + 1]] = geom_polygon(data = data.frame(poly), aes(x = x, y = y), |
| 128 | 69x | fill = fill[j], color = color[j], linewidth = linewidth) |
| 129 | } | |
| 130 | } | |
| 131 | } | |
| 132 | } | |
| 133 | 4x | ray_environment$final_polygon = TRUE |
| 134 | ! | } else if(!inherits(offset_polygons, "rayskeleton_offset_polygons_collection")) { |
| 135 | ! | stop(sprintf("`offset_polygons`` must be of class `rayskeleton_polygon` or `rayskeleton_offset_polygons_collection` (object is class `%s`)", |
| 136 | ! | class(offset_polygons))) |
| 137 | } | |
| 138 | ||
| 139 | 4x | for(i in seq_len(length(offset_polygons))) { |
| 140 | 71x | original_vertices = attr(offset_polygons[[i]], "original_vertices") |
| 141 | 71x | colnames(original_vertices) = c("x","y") |
| 142 | # If skeleton is provided and plot_original_polygon is TRUE, add original polygon and holes to the plot | |
| 143 | 71x | if (plot_original_polygon) { |
| 144 | 71x | p[[length(p) + 1]] = geom_polygon(data = data.frame(original_vertices), |
| 145 | 71x | aes(x = x, y = y), fill = NA, color = "black", linewidth = linewidth) |
| 146 | ||
| 147 | # Plot holes, if they exist | |
| 148 | 71x | original_holes = attr(offset_polygons[[i]], "original_holes") |
| 149 | 71x | if (!is.null(original_holes)) { |
| 150 | 71x | for (hole in original_holes) { |
| 151 | ! | colnames(hole) = c("x","y") |
| 152 | ! | p[[length(p) + 1]] = geom_polygon(data = data.frame(hole), |
| 153 | ! | aes(x = x, y = y), fill = NA, color = "black", linewidth = linewidth) |
| 154 | } | |
| 155 | } | |
| 156 | } | |
| 157 | } | |
| 158 | 4x | if(plot_skeleton) { |
| 159 | ! | for(i in seq_len(length(offset_polygons))) { |
| 160 | ! | p[[length(p) + 1]] = plot_skeleton(attr(offset_polygons[[i]], "skeleton"), |
| 161 | ! | return_layers = TRUE, |
| 162 | ... ) | |
| 163 | } | |
| 164 | } | |
| 165 | ||
| 166 | # Set x and y limits if provided | |
| 167 | 4x | if(ray_environment$final_polygon && !return_layers) { |
| 168 | 4x | p[[length(p) + 1]] = coord_fixed() |
| 169 | 4x | p[[length(p) + 1]] = theme_void() |
| 170 | 4x | p[[length(p) + 1]] = theme(legend.position = "none") |
| 171 | 4x | if(!is.na(background)) { |
| 172 | 4x | p[[length(p) + 1]] = theme(plot.background = element_rect(fill = background, |
| 173 | 4x | color = NA)) |
| 174 | } | |
| 175 | 4x | return(ggplot() + p) |
| 176 | } else { | |
| 177 | ! | return(p) |
| 178 | } | |
| 179 | } |
| 1 | #' Generate an offset polygon | |
| 2 | #' | |
| 3 | #' This function generates an interior offset polygon from a straight skeleton. | |
| 4 | #' | |
| 5 | #' @param skeleton Default `NULL`. A straight skeleton generated from the `skeletonize` function. | |
| 6 | #' @param offset Default `NULL`. The offset(s) of the polygon. | |
| 7 | #' @param progress Default `FALSE`. Whether to display a progress bar. | |
| 8 | #' | |
| 9 | #' @return A list of data frames, each representing a polygon offset by the specified amount. | |
| 10 | #' | |
| 11 | #' @export | |
| 12 | #' @examples | |
| 13 | #' # Simple polygon example | |
| 14 | #' simple_poly = matrix(c(0,0, 3,0, 3,3, 0,3, 0,0), ncol=2, byrow=TRUE) | |
| 15 | #' skeleton = skeletonize(simple_poly) | |
| 16 | #' offset_polys = generate_offset_polygon(skeleton, c(0.25, 0.5)) | |
| 17 | #' print(offset_polys) | |
| 18 | #' | |
| 19 | #' # Polygon with hole example | |
| 20 | #' # Outer polygon | |
| 21 | #' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE) | |
| 22 | #' # Holes inside the polygon | |
| 23 | #' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,] | |
| 24 | #' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,] | |
| 25 | #' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2)) | |
| 26 | #' if(run_docs_raybevel()) { | |
| 27 | #' plot_skeleton(skeleton) | |
| 28 | #' } | |
| 29 | #' | |
| 30 | #' #Generate three offsets | |
| 31 | #' if(run_docs_raybevel()) { | |
| 32 | #' plot_offset_polygon(generate_offset_polygon(skeleton, c(0.25,0.75,1.5,2))) | |
| 33 | #' } | |
| 34 | #' | |
| 35 | #' #Generate many offsets | |
| 36 | #' if(run_docs_raybevel()) { | |
| 37 | #' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0,2.5,by=0.1)+0.05)) | |
| 38 | #' } | |
| 39 | #' | |
| 40 | #' # Skeletonize and plot an {sf} object | |
| 41 | #' if(run_docs_raybevel()) { | |
| 42 | #' us_states = spData::us_states | |
| 43 | #' texas = us_states[us_states$NAME == "Texas",] | |
| 44 | #' texas_skeleton = skeletonize(texas) | |
| 45 | #' plot_offset_polygon(generate_offset_polygon(texas_skeleton, seq(0, 2.5, by = 0.1)), | |
| 46 | #' border = heat.colors, | |
| 47 | #' linewidth = 1) | |
| 48 | #' } | |
| 49 | generate_offset_polygon = function(skeleton, offset, progress = FALSE) { | |
| 50 | 5x | offset = offset[order(offset)] |
| 51 | 5x | if(inherits(skeleton, "rayskeleton_list")) { |
| 52 | 4x | is_list = TRUE |
| 53 | 4x | max_internal_distance = max(unlist(lapply(skeleton, \(x) max(x$nodes$time)))) |
| 54 | } else { | |
| 55 | 1x | is_list = FALSE |
| 56 | 1x | max_internal_distance = max(skeleton$nodes$time) |
| 57 | } | |
| 58 | 5x | offset = offset[offset < max_internal_distance] |
| 59 | 5x | if(length(offset) == 0) { |
| 60 | 1x | stop(sprintf("offsets are all greater than maximum internal distance (%f)",max_internal_distance)) |
| 61 | } | |
| 62 | 4x | poly_list = list() |
| 63 | 4x | if(is_list) { |
| 64 | 3x | for(j in seq_len(length(skeleton))) { |
| 65 | 70x | poly_list_skeleton = list() |
| 66 | 70x | for(i in seq_len(length(offset))) { |
| 67 | 74x | poly_list_skeleton[[i]] = generate_offset_links_nodes(skeleton[[j]], offset[i], return_polys = TRUE, |
| 68 | 74x | verbose = FALSE, progress = progress) |
| 69 | 74x | class(poly_list_skeleton[[i]]) = c("rayskeleton_offset_polygons", "list") |
| 70 | 74x | num_polygons = length(poly_list_skeleton[[i]]) |
| 71 | 74x | attr(poly_list_skeleton[[i]], "number_polygons") = num_polygons |
| 72 | 74x | offset_len = seq_len(length(num_polygons)) |
| 73 | 74x | names(poly_list_skeleton[[i]]) = sprintf("%s_off%i",offset_len,i) |
| 74 | } | |
| 75 | 70x | class(poly_list_skeleton) = c("rayskeleton_offset_polygons_collection", "list") |
| 76 | 70x | attr(poly_list_skeleton, "skeleton") = skeleton[[j]] |
| 77 | 70x | attr(poly_list_skeleton, "number_offsets") = length(offset) |
| 78 | 70x | attr(poly_list_skeleton, "original_vertices") = attr(skeleton[[j]], "original_vertices") |
| 79 | 70x | attr(poly_list_skeleton, "original_holes") = attr(skeleton[[j]], "original_holes") |
| 80 | 70x | poly_list[[j]] = poly_list_skeleton |
| 81 | } | |
| 82 | } else { | |
| 83 | 1x | poly_list_skeleton = list() |
| 84 | 1x | for(i in seq_len(length(offset))) { |
| 85 | 1x | poly_list_skeleton[[i]] = generate_offset_links_nodes(skeleton, offset[i], return_polys = TRUE, |
| 86 | 1x | verbose = FALSE, progress = progress) |
| 87 | 1x | class(poly_list_skeleton[[i]]) = c("rayskeleton_offset_polygons", "list") |
| 88 | 1x | num_polygons = length(poly_list_skeleton[[i]]) |
| 89 | 1x | attr(poly_list_skeleton[[i]], "number_polygons") = num_polygons |
| 90 | 1x | offset_len = seq_len(length(poly_list_skeleton[[i]])) |
| 91 | 1x | names(poly_list_skeleton[[i]]) = sprintf("offset_%f_%i",offset[i],i) |
| 92 | } | |
| 93 | 1x | class(poly_list_skeleton) = c("rayskeleton_offset_polygons_collection", "list") |
| 94 | 1x | attr(poly_list_skeleton, "skeleton") = skeleton |
| 95 | 1x | attr(poly_list_skeleton, "number_offsets") = length(offset) |
| 96 | 1x | attr(poly_list_skeleton, "original_vertices") = attr(skeleton, "original_vertices") |
| 97 | 1x | attr(poly_list_skeleton, "original_holes") = attr(skeleton, "original_holes") |
| 98 | 1x | poly_list[[1]] = poly_list_skeleton |
| 99 | } | |
| 100 | 4x | class(poly_list) = c("rayskeleton_polygons", "list") |
| 101 | 4x | return(poly_list) |
| 102 | } |
| 1 | #' Identify Local and Global Maxima Nodes | |
| 2 | #' | |
| 3 | #' @param straight_skeleton The straight skeleton object. | |
| 4 | #' @keywords internal | |
| 5 | #' | |
| 6 | #' @return Vector containting maxima ids | |
| 7 | identify_maxima_nodes = function(straight_skeleton) { | |
| 8 | 139x | nodes = straight_skeleton$nodes |
| 9 | 139x | links = straight_skeleton$links |
| 10 | ||
| 11 | 139x | local_maxima = list() |
| 12 | ||
| 13 | 139x | for(i in seq_len(nrow(nodes))) { |
| 14 | 9163x | node_id = nodes[i, 'id'] |
| 15 | 9163x | node_time = nodes[i, 'time'] |
| 16 | ||
| 17 | # Find neighboring nodes | |
| 18 | 9163x | neighbors = c(links[links$source == node_id, 'destination'], |
| 19 | 9163x | links[links$destination == node_id, 'source']) |
| 20 | ||
| 21 | 9163x | neighbor_times = nodes[nodes$id %in% neighbors, 'time'] |
| 22 | ||
| 23 | # Check if the node is a local maximum | |
| 24 | 9163x | if(all(node_time >= neighbor_times)) { |
| 25 | 588x | local_maxima[[i]] = node_id |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | 139x | return(unlist(local_maxima)) |
| 30 | } |
| 1 | ||
| 2 | #' Title | |
| 3 | #' | |
| 4 | #' @param v1 Vector 1 | |
| 5 | #' @param v2 Vector 2 | |
| 6 | #' | |
| 7 | #' @return Value | |
| 8 | #' @keywords internal | |
| 9 | #' | |
| 10 | #' @examples | |
| 11 | #' #None | |
| 12 | determinant2x2 = function(v1,v2) { | |
| 13 | ! | det(matrix(c(v1,v2), ncol=2,nrow=2)) |
| 14 | } | |
| 15 | ||
| 16 | #' Dot Product | |
| 17 | #' | |
| 18 | #' @param v1 Vector 1 | |
| 19 | #' @param v2 Vector 2 | |
| 20 | #' | |
| 21 | #' @return Value | |
| 22 | #' @keywords internal | |
| 23 | #' | |
| 24 | #' @examples | |
| 25 | #' #None | |
| 26 | dot = function(v1,v2) { | |
| 27 | ! | sum(v1*v2) |
| 28 | } | |
| 29 | ||
| 30 | #' Dot Product | |
| 31 | #' | |
| 32 | #' | |
| 33 | #' @return Value | |
| 34 | #' @keywords internal | |
| 35 | #' | |
| 36 | #' @examples | |
| 37 | #' #None | |
| 38 | unit_vector = function(v) { | |
| 39 | ! | v/sqrt(sum(v*v)) |
| 40 | } | |
| 41 | ||
| 42 | ||
| 43 | #' Interpolate Location | |
| 44 | #' | |
| 45 | #' @param node_start Length-2 Numeric x/y position | |
| 46 | #' @param node_end Length-2 Numeric x/y position | |
| 47 | #' @param height_start Length-1 Numeric height at start node | |
| 48 | #' @param height_end Length-1 Numeric height at end node | |
| 49 | #' @param height Length-1 Numeric height at which to interpolate | |
| 50 | #' | |
| 51 | #' @keywords internal | |
| 52 | interpolate_location = function(node_start, | |
| 53 | node_end, | |
| 54 | height_start, | |
| 55 | height_end, | |
| 56 | height) { | |
| 57 | ! | if((height_end - height_start) == 0) { |
| 58 | ! | return(node_end) |
| 59 | } | |
| 60 | ! | if(height == height_end) { |
| 61 | ! | return(node_end) |
| 62 | } | |
| 63 | ! | if(height == height_start) { |
| 64 | ! | return(node_start) |
| 65 | } | |
| 66 | ! | t = (height - height_start)/(height_end - height_start) |
| 67 | ! | return(node_start * (1 - t) + node_end * t) |
| 68 | } |
| 1 | #' Discretize and Merge Nodes | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | find_dangling_nodes = function(skeleton) { | |
| 5 | # Extract node IDs from links dataframe | |
| 6 | ! | source_nodes = unique(skeleton$links$source) |
| 7 | ! | destination_nodes = unique(skeleton$links$destination) |
| 8 | ||
| 9 | # Find nodes that don't have any link pointing to them | |
| 10 | ! | nodes_without_incoming_links = setdiff(skeleton$nodes$id, destination_nodes) |
| 11 | ||
| 12 | # Find nodes that don't have any link originating from them | |
| 13 | ! | nodes_without_outgoing_links = setdiff(skeleton$nodes$id, source_nodes) |
| 14 | ||
| 15 | # Combine the two lists and identify unique IDs | |
| 16 | ! | dangling_nodes = unique(c(nodes_without_incoming_links, nodes_without_outgoing_links)) |
| 17 | ||
| 18 | # Return the IDs of the dangling nodes | |
| 19 | ! | return(dangling_nodes) |
| 20 | } |
| 1 | #' Arrange or Reorder Rows of a Data Frame by Columns | |
| 2 | #' | |
| 3 | #' This function sorts a data frame based on the provided columns. | |
| 4 | #' | |
| 5 | #' @param data A data frame. | |
| 6 | #' @param ... Column names to determine the sort order. | |
| 7 | #' | |
| 8 | #' @return A sorted data frame. | |
| 9 | #' | |
| 10 | #' @keywords internal | |
| 11 | arrange_base = function(data, ...){ | |
| 12 | 417x | colnames = as.character(substitute(list(...))[-1]) |
| 13 | 417x | order_args = lapply(colnames, function(col) data[[col]]) |
| 14 | 417x | sorted_indices = do.call(order, order_args) |
| 15 | 417x | return(data[sorted_indices, ]) |
| 16 | } |
| 1 | #' Extrude Sides of Polygon | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | swap_yz = function(mesh) { | |
| 5 | 65x | for(i in seq_along(mesh$vertices)) { |
| 6 | 171x | mesh$vertices[[i]] = mesh$vertices[[i]][,c(1,3,2)] |
| 7 | 171x | mesh$vertices[[i]][,1] = -mesh$vertices[[i]][,1] |
| 8 | } | |
| 9 | # for(i in seq_along(mesh$shapes)) { | |
| 10 | # mesh$shapes[[i]]$indices = mesh$shapes[[i]]$indices[,3:1] | |
| 11 | # mesh$shapes[[i]]$norm_indices = mesh$shapes[[i]]$norm_indices[,3:1] | |
| 12 | # mesh$shapes[[i]]$tex_indices = mesh$shapes[[i]]$tex_indices[,3:1] | |
| 13 | # } | |
| 14 | 65x | return(mesh) |
| 15 | } |
| 1 | #' Remove Reversed Links | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | remove_reversed_links = function(skeleton) { | |
| 5 | # Create two new columns: min_id and max_id | |
| 6 | 139x | skeleton$links$min_id = pmin(skeleton$links$source, skeleton$links$destination) |
| 7 | 139x | skeleton$links$max_id = pmax(skeleton$links$source, skeleton$links$destination) |
| 8 | ||
| 9 | # Identify duplicates based on min_id and max_id | |
| 10 | 139x | dupes = duplicated(skeleton$links[, c("min_id", "max_id")]) |
| 11 | ||
| 12 | # Remove the duplicated links | |
| 13 | 139x | skeleton$links = skeleton$links[!dupes, ] |
| 14 | ||
| 15 | # Remove the temporary columns | |
| 16 | 139x | skeleton$links$min_id = NULL |
| 17 | 139x | skeleton$links$max_id = NULL |
| 18 | ||
| 19 | 139x | return(skeleton) |
| 20 | } |
| 1 | ray_environment = new.env(parent = emptyenv()) | |
| 2 | ||
| 3 | .onLoad = function(libname, pkgname) { | |
| 4 | ! | assign("init_time", 0, envir = ray_environment) |
| 5 | ! | assign("prev_time", 0, envir = ray_environment) |
| 6 | ! | assign("final_polygon", TRUE, envir = ray_environment) |
| 7 | } |
| 1 | #include <Rcpp.h> | |
| 2 | #include <vector> | |
| 3 | #include <cmath> | |
| 4 | #include <algorithm> | |
| 5 | #include <RProgress.h> | |
| 6 | ||
| 7 | #include "RcppThread.h" | |
| 8 | #include "math.h" | |
| 9 | #include <iostream> | |
| 10 | #include <vector> | |
| 11 | #include <unordered_set> | |
| 12 | #include <algorithm> | |
| 13 | #include <functional> | |
| 14 | ||
| 15 | using namespace Rcpp; | |
| 16 | ||
| 17 | // Custom hash function for a vector of integers | |
| 18 | 7432x | std::size_t vec_hash(const std::vector<int>& vec) { |
| 19 | 7432x | std::size_t seed = vec.size(); |
| 20 | 44648x | for(auto& i : vec) { |
| 21 | 29784x | seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2); |
| 22 | } | |
| 23 | 7432x | return seed; |
| 24 | } | |
| 25 | ||
| 26 | struct Node2 { | |
| 27 | int id; | |
| 28 | double x; | |
| 29 | double y; | |
| 30 | double time; | |
| 31 | int edge; | |
| 32 | }; | |
| 33 | ||
| 34 | struct Link2 { | |
| 35 | int source; | |
| 36 | int destination; | |
| 37 | int edge; | |
| 38 | double source_time; | |
| 39 | double destination_time; | |
| 40 | int visited; | |
| 41 | }; | |
| 42 | ||
| 43 | 282543x | static std::vector<double> getNodePositionById(const std::vector<Node2>& nodes, int id) { |
| 44 | 6564226x | for(const auto& node : nodes) { |
| 45 | 6369608x | if(node.id == id) { |
| 46 | 866397x | return {node.x, node.y}; |
| 47 | } | |
| 48 | } | |
| 49 | -87925x | return {}; // Empty vector if node ID is not found |
| 50 | } | |
| 51 | ||
| 52 | // Helper function definitions | |
| 53 | std::vector<double> getNodePositionById(const std::vector<Node2>& nodes, int id); | |
| 54 | double determinant2x2(const std::vector<double>& v1, const std::vector<double>& v2); | |
| 55 | double dot(const std::vector<double>& v1, const std::vector<double>& v2); | |
| 56 | ||
| 57 | // [[Rcpp::export]] | |
| 58 | 65x | List convert_ss_to_polygons_rcpp(List ss, int numbercores, bool progress) { |
| 59 | 65x | if(numbercores == NA_INTEGER || numbercores < 1) { |
| 60 | ! | numbercores = 1; |
| 61 | } | |
| 62 | ||
| 63 | 130x | List nodesDF = ss["nodes"]; |
| 64 | 130x | List linksDF = ss["links"]; |
| 65 | ||
| 66 | ||
| 67 | // Convert nodes to C++ vector of structs | |
| 68 | 130x | IntegerVector node_ids = nodesDF["id"]; |
| 69 | 130x | NumericVector node_x = nodesDF["x"]; |
| 70 | 130x | NumericVector node_y = nodesDF["y"]; |
| 71 | 130x | NumericVector node_time = nodesDF["time"]; |
| 72 | 65x | LogicalVector node_edge = nodesDF["edge"]; |
| 73 | ||
| 74 | 65x | std::vector<Node2> nodes; |
| 75 | 3846x | for(int i = 0; i < static_cast<int>(node_ids.size()); ++i) { |
| 76 | 3781x | Node2 n = {node_ids[i], node_x[i], node_y[i], node_time[i], node_edge[i]}; |
| 77 | 3781x | nodes.push_back(n); |
| 78 | } | |
| 79 | ||
| 80 | // Convert links to C++ vector of structs | |
| 81 | 130x | IntegerVector link_source = linksDF["source"]; |
| 82 | 130x | IntegerVector link_dest = linksDF["destination"]; |
| 83 | 130x | LogicalVector link_edge = linksDF["edge"]; |
| 84 | 130x | NumericVector link_source_time = linksDF["source_time"]; |
| 85 | 65x | NumericVector link_dest_time = linksDF["destination_time"]; |
| 86 | ||
| 87 | 65x | std::vector<Link2> links; |
| 88 | 7497x | for(int i = 0; i < static_cast<int>(link_source.size()); ++i) { |
| 89 | 7432x | Link2 l = {link_source[i], link_dest[i], link_edge[i], link_source_time[i], link_dest_time[i], false}; |
| 90 | 7432x | links.push_back(l); |
| 91 | } | |
| 92 | 65x | RcppThread::ProgressCounter pb(link_source.size(), 1, "Polygonizing: "); |
| 93 | 65x | std::vector<std::vector<int>> list_all_polygons; |
| 94 | 65x | list_all_polygons.resize(links.size()); |
| 95 | // for(int k = 0; k< links.size(); k++) { | |
| 96 | 65x | RcppThread::parallelFor(static_cast<size_t>(0), links.size(), [&links, &nodes, &list_all_polygons, &pb, &progress] (size_t k) { |
| 97 | 7390x | bool first = true; |
| 98 | 7390x | int first_node = links[k].source; |
| 99 | 7392x | int tmp_source = first_node; |
| 100 | 7392x | int first_dest = links[k].destination; |
| 101 | 7392x | int tmp_dest = first_dest; |
| 102 | 7392x | std::vector<int> single_polygon_indices; |
| 103 | ||
| 104 | while(true) { | |
| 105 | 37019x | if(tmp_source == first_node && tmp_dest == first_dest && !first) { |
| 106 | 7426x | break; |
| 107 | } | |
| 108 | 29593x | first = false; |
| 109 | ||
| 110 | 29593x | std::vector<double> node1_position = getNodePositionById(nodes, tmp_source); |
| 111 | 29506x | std::vector<double> node2_position = getNodePositionById(nodes, tmp_dest); |
| 112 | ||
| 113 | 29503x | std::vector<double> node1_position_first = getNodePositionById(nodes, first_node); |
| 114 | 29493x | std::vector<double> node2_position_first = getNodePositionById(nodes, first_dest); |
| 115 | ||
| 116 | // RcppThread::Rcout << first_node << " " << tmp_source << " " << first_dest << " " << tmp_dest << "\n"; | |
| 117 | // RcppThread::Rcout << node1_position_first[0] << " " << node1_position_first[1] << " " << | |
| 118 | // node1_position[0] << " " << node1_position[1] << " | " << node2_position_first[0] << " " << node2_position_first[1] << " " << | |
| 119 | // node2_position[0] << " " << node2_position[1] <<"\n"; | |
| 120 | ||
| 121 | ||
| 122 | // Calculate the direction vector v1 for the current link | |
| 123 | 59126x | std::vector<double> v1 = {node2_position[0] - node1_position[0], node2_position[1] - node1_position[1]}; |
| 124 | ||
| 125 | 29562x | double best_angle = 180.0; |
| 126 | 29562x | int best_dest = -1; |
| 127 | 29562x | int best_source = -1; |
| 128 | 29562x | double best_len = std::numeric_limits<double>::infinity(); |
| 129 | ||
| 130 | // Loop over all candidate next links | |
| 131 | 2947309x | for(const auto& link : links) { |
| 132 | 2878059x | if((link.destination == tmp_dest && link.source == tmp_source) || |
| 133 | 2861483x | (link.source == tmp_dest && link.destination == tmp_source)) { |
| 134 | 2832261x | continue; |
| 135 | } | |
| 136 | ||
| 137 | 2848378x | if(link.source != tmp_dest && link.destination != tmp_dest) { |
| 138 | 2802580x | continue; |
| 139 | } | |
| 140 | ||
| 141 | int candidate_source, candidate_dest; | |
| 142 | 45798x | if(link.destination == tmp_dest) { |
| 143 | 43486x | candidate_source = link.destination; |
| 144 | 43486x | candidate_dest = link.source; |
| 145 | } else { | |
| 146 | 2312x | candidate_source = link.source; |
| 147 | 2312x | candidate_dest = link.destination; |
| 148 | } | |
| 149 | ||
| 150 | // Calculate the direction vector v2 for the candidate link | |
| 151 | 45798x | std::vector<double> cs_position = getNodePositionById(nodes, candidate_source); |
| 152 | 88734x | std::vector<double> cd_position = getNodePositionById(nodes, candidate_dest); |
| 153 | 179468x | std::vector<double> v2 = {cd_position[0] - cs_position[0], cd_position[1] - cs_position[1]}; |
| 154 | ||
| 155 | // Calculate angle between v1 and v2 | |
| 156 | 89343x | double det_val = determinant2x2(v1, v2); |
| 157 | 90102x | double dot_val = dot(v1, v2); |
| 158 | 90000x | double angle = std::atan2(det_val, dot_val) * 180.0 / M_PI; |
| 159 | ||
| 160 | // Check if this angle is the smallest so far | |
| 161 | 90000x | double length_v2 = dot(v2, v2); |
| 162 | 90251x | if((angle < best_angle) || (angle == best_angle && best_len > length_v2)) { |
| 163 | 53450x | best_angle = angle; |
| 164 | ||
| 165 | 53450x | best_dest = candidate_dest; |
| 166 | 53450x | best_source = candidate_source; |
| 167 | 53450x | best_len = length_v2; |
| 168 | } | |
| 169 | } | |
| 170 | 39688x | if(best_source < 0 || best_dest < 0) { |
| 171 | 9978x | throw std::runtime_error("Didn't find candidate"); |
| 172 | } | |
| 173 | ||
| 174 | // Update tmp_source and tmp_dest for the next iteration | |
| 175 | 29710x | tmp_source = best_source; |
| 176 | 29710x | tmp_dest = best_dest; |
| 177 | 29710x | single_polygon_indices.push_back(best_dest); |
| 178 | } | |
| 179 | 7426x | if(progress) { |
| 180 | ! | pb++; |
| 181 | } | |
| 182 | 7426x | list_all_polygons[k] = single_polygon_indices; |
| 183 | 7411x | }, static_cast<size_t>(numbercores)); |
| 184 | // } | |
| 185 | ||
| 186 | // Here I'm doing the sorting and hashing in C++ | |
| 187 | 65x | std::unordered_map<std::size_t, bool> seen_hashes; |
| 188 | 65x | std::vector<std::vector<int>> unique_polygons; |
| 189 | ||
| 190 | 7562x | for (const auto& polygon : list_all_polygons) { |
| 191 | 7432x | std::vector<int> sorted_polygon = polygon; |
| 192 | 7432x | std::sort(sorted_polygon.begin(), sorted_polygon.end()); |
| 193 | 7432x | std::size_t hash = vec_hash(sorted_polygon); |
| 194 | ||
| 195 | 7432x | if (seen_hashes.find(hash) == seen_hashes.end()) { |
| 196 | // This is a unique polygon, save it and mark it as seen | |
| 197 | 3588x | unique_polygons.push_back(polygon); |
| 198 | 3588x | seen_hashes[hash] = true; |
| 199 | } | |
| 200 | } | |
| 201 | ||
| 202 | 65x | List all_polygons; |
| 203 | 3653x | for(int i = 0; i < static_cast<int>(unique_polygons.size()); i++) { |
| 204 | 3588x | IntegerVector one_polygon; |
| 205 | 17680x | for(int j = 0; j < static_cast<int>(unique_polygons[i].size()); j++) { |
| 206 | 14092x | one_polygon.push_back(unique_polygons[i][j]); |
| 207 | } | |
| 208 | 3588x | all_polygons.push_back(one_polygon); |
| 209 | } | |
| 210 | ||
| 211 | 65x | return all_polygons; |
| 212 | } |
| 1 | #include <Rcpp.h> | |
| 2 | #include <vector> | |
| 3 | #include <cmath> | |
| 4 | #include "math.h" | |
| 5 | #include "RProgress.h" | |
| 6 | ||
| 7 | using namespace Rcpp; | |
| 8 | ||
| 9 | struct Node { | |
| 10 | int id; | |
| 11 | double x; | |
| 12 | double y; | |
| 13 | double time; | |
| 14 | int edge; | |
| 15 | int local_maxima; | |
| 16 | }; | |
| 17 | ||
| 18 | struct Link { | |
| 19 | int source; | |
| 20 | int destination; | |
| 21 | int edge; | |
| 22 | int maxima_source; | |
| 23 | int maxima_dest; | |
| 24 | int visited; | |
| 25 | double source_time; | |
| 26 | double destination_time; | |
| 27 | }; | |
| 28 | ||
| 29 | struct NewNode { | |
| 30 | int polygon_id; | |
| 31 | int source; | |
| 32 | int destination; | |
| 33 | int new_id; | |
| 34 | double x; | |
| 35 | double y; | |
| 36 | double time; | |
| 37 | double x1; | |
| 38 | double y1; | |
| 39 | double x2; | |
| 40 | double y2; | |
| 41 | int new_node; | |
| 42 | }; | |
| 43 | ||
| 44 | 97034x | static std::vector<double> getNodePositionById(const std::vector<Node>& nodes, int id) { |
| 45 | 7638791x | for(const auto& node : nodes) { |
| 46 | 7541757x | if(node.id == id) { |
| 47 | 291102x | return {node.x, node.y}; |
| 48 | } | |
| 49 | } | |
| 50 | ! | return {}; // Empty vector if node ID is not found |
| 51 | } | |
| 52 | ||
| 53 | 38314x | double getNodeTimeById(const std::vector<Node>& nodes, int id) { |
| 54 | 2938832x | for(const auto& node : nodes) { |
| 55 | 2900518x | if(node.id == id) { |
| 56 | 38314x | return node.time; |
| 57 | } | |
| 58 | } | |
| 59 | ! | return -1; // Empty vector if node ID is not found |
| 60 | } | |
| 61 | ||
| 62 | // Convert DataFrame to std::vector of Nodes | |
| 63 | 120x | std::vector<Node> convertDataFrameToNodes(DataFrame df) { |
| 64 | 120x | size_t nrows = df.nrow(); |
| 65 | 240x | IntegerVector id = Rcpp::as<IntegerVector>(df["id"]); |
| 66 | 240x | NumericVector x = Rcpp::as<NumericVector>(df["x"]); |
| 67 | 240x | NumericVector y = Rcpp::as<NumericVector>(df["y"]); |
| 68 | 240x | NumericVector time = Rcpp::as<NumericVector>(df["time"]); |
| 69 | 240x | IntegerVector edge = Rcpp::as<IntegerVector>(df["edge"]); |
| 70 | 240x | IntegerVector maxima = Rcpp::as<IntegerVector>(df["local_maxima"]); |
| 71 | ||
| 72 | 120x | std::vector<Node> nodes; |
| 73 | 120x | nodes.resize(nrows); |
| 74 | 9013x | for (size_t i = 0; i < nrows; ++i) { |
| 75 | 8893x | nodes[i].id = id(i); |
| 76 | 8893x | nodes[i].x = x(i); |
| 77 | 8893x | nodes[i].y = y(i); |
| 78 | 8893x | nodes[i].time = time(i); |
| 79 | 8893x | nodes[i].edge = edge(i); |
| 80 | 8893x | nodes[i].local_maxima = maxima(i); |
| 81 | } | |
| 82 | 120x | return nodes; |
| 83 | } | |
| 84 | ||
| 85 | 5226x | std::vector<double> interpolate_location(const std::vector<double>& node_start, |
| 86 | const std::vector<double>& node_end, | |
| 87 | double height_start, | |
| 88 | double height_end, | |
| 89 | double height) { | |
| 90 | // Initialize result vector | |
| 91 | 5226x | std::vector<double> result(2, 0.0); |
| 92 | ||
| 93 | // Handling edge cases | |
| 94 | 5226x | if (height_end - height_start == 0.0) { |
| 95 | ! | return node_end; |
| 96 | } | |
| 97 | 5226x | if (height == height_end) { |
| 98 | ! | return node_end; |
| 99 | } | |
| 100 | 5226x | if (height == height_start) { |
| 101 | ! | return node_start; |
| 102 | } | |
| 103 | ||
| 104 | // Calculate interpolation factor t | |
| 105 | 5226x | double t = (height - height_start) / (height_end - height_start); |
| 106 | ||
| 107 | // Perform the interpolation | |
| 108 | 5226x | result[0] = node_start[0] * (1 - t) + node_end[0] * t; |
| 109 | 5226x | result[1] = node_start[1] * (1 - t) + node_end[1] * t; |
| 110 | ||
| 111 | 5226x | return result; |
| 112 | } | |
| 113 | ||
| 114 | // Convert DataFrame to std::vector of Links | |
| 115 | 120x | std::vector<Link> convertDataFrameToLinks(DataFrame df) { |
| 116 | 120x | size_t nrows = df.nrow(); |
| 117 | 240x | IntegerVector source = Rcpp::as<IntegerVector>(df["source"]); |
| 118 | 240x | IntegerVector destination = Rcpp::as<IntegerVector>(df["destination"]); |
| 119 | 240x | LogicalVector edge = Rcpp::as<LogicalVector>(df["edge"]); |
| 120 | 240x | NumericVector source_time = Rcpp::as<NumericVector>(df["source_time"]); |
| 121 | 240x | NumericVector destination_time = Rcpp::as<NumericVector>(df["destination_time"]); |
| 122 | 240x | LogicalVector local_maxima_destination = Rcpp::as<LogicalVector>(df["local_maxima_destination"]); |
| 123 | 240x | LogicalVector local_maxima_source = Rcpp::as<LogicalVector>(df["local_maxima_source"]); |
| 124 | ||
| 125 | 120x | std::vector<Link> links; |
| 126 | 120x | links.resize(nrows); |
| 127 | ||
| 128 | 13620x | for (size_t i = 0; i < nrows; ++i) { |
| 129 | 13500x | links[i].source = (int)source(i); |
| 130 | 13500x | links[i].destination = (int)destination(i); |
| 131 | 13500x | links[i].edge = (int)edge(i); |
| 132 | 13500x | links[i].source_time = (double)source_time(i); |
| 133 | 13500x | links[i].destination_time = (double)destination_time(i); |
| 134 | 13500x | links[i].maxima_source = (int)local_maxima_source(i); |
| 135 | 13500x | links[i].maxima_dest = (int)local_maxima_destination(i); |
| 136 | 13500x | links[i].visited = (int)0; |
| 137 | } | |
| 138 | 120x | return links; |
| 139 | } | |
| 140 | ||
| 141 | // [[Rcpp::export]] | |
| 142 | 120x | List generate_offset_links_nodes_rcpp(DataFrame ss_links, DataFrame ss_nodes, NumericVector offsets, bool return_polys = false, bool progress = false) { |
| 143 | ||
| 144 | 120x | std::vector<Link> links = convertDataFrameToLinks(ss_links); |
| 145 | 120x | std::vector<Node> nodes = convertDataFrameToNodes(ss_nodes); |
| 146 | ||
| 147 | 120x | int max_node = -1; |
| 148 | 9013x | for(size_t ii = 0; ii < (size_t)nodes.size(); ii++) { |
| 149 | 8893x | max_node = std::max(nodes[ii].id,max_node); |
| 150 | } | |
| 151 | 120x | int new_node_start = max_node + 1; |
| 152 | ||
| 153 | 120x | List return_data; |
| 154 | ||
| 155 | // Initialize containers for new links and nodes | |
| 156 | 120x | std::vector<Link> newLinks; |
| 157 | 120x | std::vector<Node> newNodes; |
| 158 | ||
| 159 | // Main loop to iterate over offsets | |
| 160 | 240x | RProgress::RProgress pb("Inserting links: :percent (:eta remaining)"); |
| 161 | 120x | if(progress) { |
| 162 | ! | pb.set_total(offsets.size()); |
| 163 | ! | pb.tick(0); |
| 164 | } | |
| 165 | 496x | for(size_t ii = 0; ii < (size_t)offsets.size(); ++ii) { |
| 166 | 376x | if(progress) { |
| 167 | ! | pb.tick(ii); |
| 168 | } | |
| 169 | 376x | double offset = offsets[ii]; |
| 170 | 752x | std::vector<bool> visited(links.size()); |
| 171 | 752x | std::vector<bool> away_from_offset(links.size()); |
| 172 | 376x | std::vector<bool> equal_to_offset(links.size()); |
| 173 | 376x | std::vector<NewNode> new_node_info; |
| 174 | ||
| 175 | 22580x | for(size_t jj = 0; jj < links.size(); jj++) { |
| 176 | 22204x | visited[jj] = (bool)links[jj].edge; |
| 177 | 32513x | away_from_offset[jj] = (links[jj].source_time < offset && links[jj].destination_time < offset) || |
| 178 | 32513x | (links[jj].source_time > offset && links[jj].destination_time > offset); |
| 179 | 22204x | equal_to_offset[jj] = links[jj].source_time == offset; |
| 180 | } | |
| 181 | ||
| 182 | 376x | int first_node = -1; |
| 183 | 376x | int first_dest = -1; |
| 184 | 376x | int tmp_source = -1; |
| 185 | 376x | int tmp_dest = -1; |
| 186 | 376x | int num_polygons = 1; |
| 187 | 376x | bool first = true; |
| 188 | 376x | bool any_picked = false; |
| 189 | 376x | bool new_poly = true; |
| 190 | ||
| 191 | 13482x | for(size_t jj = 0; jj < links.size(); jj++) { |
| 192 | 13482x | if(links[jj].maxima_dest && links[jj].destination_time >= offset) { |
| 193 | 376x | first_node = links[jj].source; |
| 194 | 376x | first_dest = links[jj].destination; |
| 195 | 376x | tmp_source = first_node; |
| 196 | 376x | tmp_dest = first_dest; |
| 197 | 376x | break; |
| 198 | } | |
| 199 | } | |
| 200 | ||
| 201 | while(true) { | |
| 202 | 19401x | Rcpp::checkUserInterrupt(); |
| 203 | // if(tmp_source == first_node && tmp_dest == first_dest && !first) { | |
| 204 | // break; | |
| 205 | // } | |
| 206 | 19401x | std::vector<Link> non_visited_links; |
| 207 | 3234453x | for(size_t jj = 0; jj < links.size(); ++jj) { |
| 208 | 3215052x | if(!visited[jj]) { |
| 209 | 1220830x | non_visited_links.push_back(links[jj]); |
| 210 | } | |
| 211 | 3215052x | if(non_visited_links.size() > links.size()) { |
| 212 | ! | throw std::runtime_error("Memory corruption"); |
| 213 | } | |
| 214 | } | |
| 215 | 19401x | std::vector<Link> remaining_links; |
| 216 | 19401x | if(!first || any_picked) { |
| 217 | 19025x | if(tmp_source < 0 || tmp_dest < 0) { |
| 218 | ! | throw std::runtime_error("Bug or malformed input: next node not found"); |
| 219 | } | |
| 220 | 19025x | if(tmp_source == first_node && tmp_dest == first_dest) { |
| 221 | 1217x | new_poly = true; |
| 222 | 54850x | for(size_t jj = 0; jj < links.size(); ++jj) { |
| 223 | 53633x | if(!visited[jj] && !away_from_offset[jj] && !links[jj].edge) { |
| 224 | 10561x | remaining_links.push_back(links[jj]); |
| 225 | } | |
| 226 | } | |
| 227 | 1217x | if(remaining_links.size() == 0) { |
| 228 | 244x | break; |
| 229 | } | |
| 230 | 973x | first_node = remaining_links[0].source; |
| 231 | 973x | first_dest = remaining_links[0].destination; |
| 232 | 973x | tmp_source = first_node; |
| 233 | 973x | tmp_dest = first_dest; |
| 234 | 973x | num_polygons++; |
| 235 | } | |
| 236 | } | |
| 237 | // size_t remaining_links_count = std::count_if(visited.begin(), visited.end(), [](bool l) { return !l; }); | |
| 238 | ||
| 239 | 19157x | first = false; |
| 240 | ||
| 241 | 19157x | std::vector<double> node1_position = getNodePositionById(nodes, tmp_source); |
| 242 | 19157x | std::vector<double> node2_position = getNodePositionById(nodes, tmp_dest); |
| 243 | 19157x | double node1_time = getNodeTimeById(nodes, tmp_source); |
| 244 | 19157x | double node2_time = getNodeTimeById(nodes, tmp_dest); |
| 245 | ||
| 246 | 3216828x | for(size_t jj = 0; jj < links.size(); jj++) { |
| 247 | 3197671x | if((links[jj].source == tmp_source && |
| 248 | 6385390x | links[jj].destination == tmp_dest) || |
| 249 | 3187719x | (links[jj].destination == tmp_source && |
| 250 | 38688x | links[jj].source == tmp_dest)) { |
| 251 | 19157x | visited[jj] = true; |
| 252 | } | |
| 253 | } | |
| 254 | 19157x | std::vector<double> node_position_new; |
| 255 | 19157x | if(offset >= node1_time && offset < node2_time) { |
| 256 | 5717x | if(new_poly) { |
| 257 | 645x | first_node = tmp_source; |
| 258 | 645x | first_dest = tmp_dest; |
| 259 | } | |
| 260 | int node_val; | |
| 261 | 5717x | bool make_new_node = true; |
| 262 | 5717x | if(node1_time == offset) { |
| 263 | 491x | make_new_node = false; |
| 264 | 491x | node_position_new = node1_position; |
| 265 | 491x | node_val = tmp_source; |
| 266 | 5226x | } else if (node2_time == offset) { |
| 267 | ! | make_new_node = false; |
| 268 | ! | node_position_new = node2_position; |
| 269 | ! | node_val = tmp_dest; |
| 270 | } else { | |
| 271 | 10452x | node_position_new = interpolate_location(node1_position,node2_position, |
| 272 | 5226x | node1_time,node2_time,offset); |
| 273 | 5226x | node_val = new_node_start; |
| 274 | } | |
| 275 | ||
| 276 | NewNode new_node = {num_polygons, tmp_source, tmp_dest, node_val, | |
| 277 | 11434x | node_position_new[0], node_position_new[1], |
| 278 | 11434x | offset, node1_position[0], node1_position[1], |
| 279 | 11434x | node2_position[0],node2_position[1], |
| 280 | 5717x | make_new_node}; |
| 281 | 5717x | new_node_info.push_back(new_node); |
| 282 | ||
| 283 | 5717x | if(make_new_node) { |
| 284 | 5226x | new_node_start++; |
| 285 | } | |
| 286 | 5717x | new_poly = false; |
| 287 | } else { | |
| 288 | 13440x | if(new_poly) { |
| 289 | 751x | first_node = tmp_source; |
| 290 | 751x | first_dest = tmp_dest; |
| 291 | } | |
| 292 | } | |
| 293 | ||
| 294 | // bool all_remaining_at_offset = true; | |
| 295 | // for(int jj = 0; jj < non_visited_links.size(); jj++) { | |
| 296 | // if(((non_visited_links[jj].destination_time == offset && non_visited_links[jj].maxima_dest) || | |
| 297 | // (non_visited_links[jj].source_time == offset && non_visited_links[jj].maxima_source)) && | |
| 298 | // new_poly) { | |
| 299 | // Rcpp::Rcout << "All remaining offset \n"; | |
| 300 | // } else { | |
| 301 | // all_remaining_at_offset = false; | |
| 302 | // } | |
| 303 | // } | |
| 304 | // if(all_remaining_at_offset) { | |
| 305 | // break; | |
| 306 | // } | |
| 307 | ||
| 308 | 19157x | bool is_edge = false; |
| 309 | 2137631x | for(size_t jj = 0; jj < nodes.size(); jj++) { |
| 310 | 2118474x | if(nodes[jj].id == tmp_dest) { |
| 311 | 19157x | is_edge = nodes[jj].edge; |
| 312 | } | |
| 313 | } | |
| 314 | // Rcpp::Rcout << offset << " " << node1_time << " " << node2_time << " " << | |
| 315 | // first_node << " " << first_dest << " " << tmp_source << " " << tmp_dest << " " << remaining_links_count << " " << | |
| 316 | // is_edge << " " << bool((node1_time - offset) == 0) << " " << bool((node2_time - offset) == 0) << "\n"; | |
| 317 | // Rcpp::Rcout << tmp_source << " " << tmp_dest << " " << offset << " " << | |
| 318 | // remaining_links_count << "\n"; | |
| 319 | // | |
| 320 | 19157x | if((offset < node1_time && offset >= node2_time) || |
| 321 | is_edge) { | |
| 322 | 5663x | int new_source = tmp_dest; |
| 323 | 5663x | int new_dest = tmp_source; |
| 324 | 5663x | tmp_source = new_source; |
| 325 | 5663x | tmp_dest = new_dest; |
| 326 | 5663x | continue; |
| 327 | } | |
| 328 | ||
| 329 | // Calculate the direction vector v1 for the current link | |
| 330 | 26988x | std::vector<double> v1 = {node2_position[0] - node1_position[0], node2_position[1] - node1_position[1]}; |
| 331 | ||
| 332 | 13494x | double best_angle = 180.0; |
| 333 | 13494x | int best_dest = -1; |
| 334 | 13494x | int best_source = -1; |
| 335 | 13494x | double best_len = std::numeric_limits<double>::infinity(); |
| 336 | 13494x | any_picked = false; |
| 337 | ||
| 338 | // Loop over all candidate next links | |
| 339 | 2376203x | for(const auto& link : links) { |
| 340 | 2349215x | if((link.destination == tmp_dest && link.source == tmp_source) || |
| 341 | 2339263x | (link.source == tmp_dest && link.destination == tmp_source)) { |
| 342 | 2319855x | continue; |
| 343 | } | |
| 344 | ||
| 345 | 2335721x | if(link.source != tmp_dest && link.destination != tmp_dest) { |
| 346 | 2304569x | continue; |
| 347 | } | |
| 348 | ||
| 349 | 31152x | if(link.edge) { |
| 350 | ! | continue; |
| 351 | } | |
| 352 | 31152x | if(node2_time == offset) { |
| 353 | 1792x | if(!(tmp_dest == link.source && link.destination_time >= offset) || |
| 354 | 1024x | !(tmp_dest == link.destination && link.source_time >= offset)) { |
| 355 | 1792x | continue; |
| 356 | } | |
| 357 | } | |
| 358 | // if(node2_time == offset) { | |
| 359 | // if((tmp_dest == link.source && link.destination_time >= offset) || | |
| 360 | // (tmp_dest == link.destination && link.source_time >= offset)) { | |
| 361 | // continue; | |
| 362 | // } | |
| 363 | // } | |
| 364 | 29360x | if(link.destination == tmp_dest && link.maxima_dest && link.destination_time == offset) { |
| 365 | ! | continue; |
| 366 | } | |
| 367 | 29360x | if(tmp_dest == link.source && link.maxima_source && link.source_time == offset) { |
| 368 | ! | continue; |
| 369 | } | |
| 370 | 29360x | any_picked = true; |
| 371 | ||
| 372 | int candidate_source, candidate_dest; | |
| 373 | 29360x | if(link.destination == tmp_dest) { |
| 374 | 21670x | candidate_source = link.destination; |
| 375 | 21670x | candidate_dest = link.source; |
| 376 | } else { | |
| 377 | 7690x | candidate_source = link.source; |
| 378 | 7690x | candidate_dest = link.destination; |
| 379 | } | |
| 380 | ||
| 381 | // Calculate the direction vector v2 for the candidate link | |
| 382 | 29360x | std::vector<double> cs_position = getNodePositionById(nodes, candidate_source); |
| 383 | 29360x | std::vector<double> cd_position = getNodePositionById(nodes, candidate_dest); |
| 384 | 58720x | std::vector<double> v2 = {cd_position[0] - cs_position[0], cd_position[1] - cs_position[1]}; |
| 385 | ||
| 386 | // Calculate angle between v1 and v2 | |
| 387 | 29360x | double det_val = determinant2x2(v1, v2); |
| 388 | 29360x | double dot_val = dot(v1, v2); |
| 389 | 29360x | double angle = std::atan2(det_val, dot_val) * 180.0 / M_PI; |
| 390 | ||
| 391 | // Check if this angle is the smallest so far | |
| 392 | 29360x | double length_v2 = dot(v2, v2); |
| 393 | 29360x | if((angle < best_angle) || (angle == best_angle && best_len > length_v2)) { |
| 394 | 20566x | best_angle = angle; |
| 395 | ||
| 396 | 20566x | best_dest = candidate_dest; |
| 397 | 20566x | best_source = candidate_source; |
| 398 | 20566x | best_len = length_v2; |
| 399 | } | |
| 400 | } | |
| 401 | 13494x | if(any_picked) { |
| 402 | 12790x | tmp_source = best_source; |
| 403 | 12790x | tmp_dest = best_dest; |
| 404 | } | |
| 405 | 13494x | bool all_remaining_at_offset = true; |
| 406 | 910211x | for(size_t jj = 0; jj < non_visited_links.size(); jj++) { |
| 407 | 905101x | if(((non_visited_links[jj].destination_time == offset && non_visited_links[jj].maxima_dest) || |
| 408 | 905101x | (non_visited_links[jj].source_time == offset && non_visited_links[jj].maxima_source)) && |
| 409 | new_poly) { | |
| 410 | // Rcpp::Rcout << "All remaining offset \n"; | |
| 411 | } else { | |
| 412 | 893581x | all_remaining_at_offset = false; |
| 413 | } | |
| 414 | } | |
| 415 | 13494x | if(all_remaining_at_offset) { |
| 416 | 132x | break; |
| 417 | } | |
| 418 | // if(best_source < 0 || best_dest < 0) { | |
| 419 | // throw std::runtime_error("Didn't find candidate"); | |
| 420 | // } | |
| 421 | } | |
| 422 | 376x | List single_offset_nodes; |
| 423 | 6093x | for(size_t jj = 0; jj < new_node_info.size(); jj++) { |
| 424 | 5717x | NewNode& x = new_node_info[jj]; |
| 425 | 5717x | NumericVector node_data = {(double)x.polygon_id, |
| 426 | 5717x | (double)x.source, |
| 427 | 5717x | (double)x.destination, |
| 428 | 5717x | (double)x.new_id, |
| 429 | 5717x | x.x, |
| 430 | 5717x | x.y, |
| 431 | 5717x | x.time, |
| 432 | 5717x | x.x1, |
| 433 | 5717x | x.y1, |
| 434 | 5717x | x.x2, |
| 435 | 5717x | x.y2, |
| 436 | 5717x | (double)x.new_node}; |
| 437 | 5717x | single_offset_nodes.push_back(node_data); |
| 438 | } | |
| 439 | 376x | return_data.push_back(single_offset_nodes); |
| 440 | } | |
| 441 | 120x | return(return_data); |
| 442 | } |
| 1 | #include "math.h" | |
| 2 | ||
| 3 | // Helper function to calculate determinant of two 2D vectors | |
| 4 | 118640x | double determinant2x2(const std::vector<double>& v1, const std::vector<double>& v2) { |
| 5 | 118640x | return v1[0] * v2[1] - v1[1] * v2[0]; |
| 6 | } | |
| 7 | ||
| 8 | // Helper function to calculate dot product of two 2D vectors | |
| 9 | 237643x | double dot(const std::vector<double>& v1, const std::vector<double>& v2) { |
| 10 | 237643x | return v1[0] * v2[0] + v1[1] * v2[1]; |
| 11 | } |
| 1 | #include <Rcpp.h> | |
| 2 | using namespace Rcpp; | |
| 3 | ||
| 4 | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> | |
| 5 | #include <CGAL/Polygon_2.h> | |
| 6 | #include <CGAL/Polygon_with_holes_2.h> | |
| 7 | #include <CGAL/Polygon_set_2.h> | |
| 8 | #include <CGAL/create_straight_skeleton_from_polygon_with_holes_2.h> | |
| 9 | #include <CGAL/create_offset_polygons_2.h> | |
| 10 | #include <CGAL/Boolean_set_operations_2/Gps_polygon_validation.h> | |
| 11 | #include <CGAL/Boolean_set_operations_2.h> | |
| 12 | #include <CGAL/General_polygon_set_2.h> | |
| 13 | #include "print.h" | |
| 14 | #include <vector> | |
| 15 | #include <cassert> | |
| 16 | ||
| 17 | ||
| 18 | #define is_inside(os) ((os == CGAL::ON_ORIENTED_BOUNDARY) ? true : \ | |
| 19 | (os == CGAL::POSITIVE) ? true : false) | |
| 20 | ||
| 21 | typedef CGAL::Exact_predicates_inexact_constructions_kernel K ; | |
| 22 | typedef K::Point_2 Point ; | |
| 23 | typedef CGAL::Polygon_2<K> Polygon_2 ; | |
| 24 | // typedef CGAL::Polygon_set_2<K> PolygonSet; | |
| 25 | typedef CGAL::Straight_skeleton_2<K> Ss ; | |
| 26 | typedef std::shared_ptr<Polygon_2> PolygonPtr ; | |
| 27 | typedef std::shared_ptr<Ss> SsPtr ; | |
| 28 | typedef std::vector<PolygonPtr> PolygonPtrVector ; | |
| 29 | typedef CGAL::Polygon_with_holes_2<K> Polygon_with_holes ; | |
| 30 | typedef CGAL::Gps_segment_traits_2<K> Traits_2; | |
| 31 | ||
| 32 | ||
| 33 | typedef typename Ss::Vertex_const_handle Vertex_const_handle ; | |
| 34 | typedef typename Ss::Halfedge_const_handle Halfedge_const_handle ; | |
| 35 | typedef typename Ss::Halfedge_const_iterator Halfedge_const_iterator ; | |
| 36 | ||
| 37 | // [[Rcpp::export]] | |
| 38 | 278x | bool is_ccw_polygon(NumericMatrix vertices) { |
| 39 | 278x | Polygon_2 base_poly; |
| 40 | 14874x | for(int i = 0; i < vertices.rows(); i++) { |
| 41 | 14596x | base_poly.push_back(Point(vertices(i,0),vertices(i,1))); |
| 42 | } | |
| 43 | 278x | if(base_poly.is_counterclockwise_oriented()) { |
| 44 | 139x | return(true); |
| 45 | } else { | |
| 46 | 139x | return(false); |
| 47 | } | |
| 48 | } | |
| 49 | ||
| 50 | // [[Rcpp::export]] | |
| 51 | 2x | bool is_simple_polygon(NumericMatrix vertices) { |
| 52 | 2x | Polygon_2 base_poly; |
| 53 | 10x | for(int i = 0; i < vertices.rows(); i++) { |
| 54 | 8x | base_poly.push_back(Point(vertices(i,0),vertices(i,1))); |
| 55 | } | |
| 56 | 2x | if(base_poly.is_simple()) { |
| 57 | 2x | return(true); |
| 58 | } else { | |
| 59 | ! | return(false); |
| 60 | } | |
| 61 | } | |
| 62 | ||
| 63 | // [[Rcpp::export]] | |
| 64 | 139x | List skeletonize_rcpp(NumericMatrix vertices, |
| 65 | List holes, | |
| 66 | double offset) { | |
| 67 | 139x | Polygon_2 base_poly; |
| 68 | 7437x | for(int i = 0; i < vertices.rows(); i++) { |
| 69 | // Rcpp::Rcout << "Vert: " << vertices(i,0) << " " << vertices(i,1) << "\n"; | |
| 70 | ||
| 71 | 7298x | base_poly.push_back(Point(vertices(i,0),vertices(i,1))); |
| 72 | } | |
| 73 | 139x | if(!base_poly.is_counterclockwise_oriented()) { |
| 74 | ! | throw std::runtime_error("raybevel: Polygon is not CCW oriented."); |
| 75 | } | |
| 76 | 139x | if(!base_poly.is_simple()) { |
| 77 | ! | throw std::runtime_error("raybevel: Polygon is not simple."); |
| 78 | } | |
| 79 | 139x | Polygon_with_holes poly(base_poly); |
| 80 | ||
| 81 | 141x | for(int i = 0; i < holes.length(); i++) { |
| 82 | 2x | Polygon_2 new_hole; |
| 83 | 2x | bool all_inside = true; |
| 84 | 2x | NumericMatrix hole = Rcpp::as<NumericMatrix>(holes(i)); |
| 85 | 10x | for(int i = 0; i < hole.rows(); i++) { |
| 86 | 8x | Point tmp_point(hole(i,0),hole(i,1)); |
| 87 | 8x | if(!is_inside(base_poly.oriented_side(tmp_point))) { |
| 88 | ! | all_inside = false; |
| 89 | ! | break; |
| 90 | } | |
| 91 | 8x | new_hole.push_back(tmp_point); |
| 92 | } | |
| 93 | 2x | if(all_inside) { |
| 94 | // if(!new_hole.is_clockwise_oriented()) { | |
| 95 | // throw std::runtime_error("rayskeleton: Hole in polygon is not CW oriented."); | |
| 96 | // } | |
| 97 | // if(!new_hole.is_simple()) { | |
| 98 | // throw std::runtime_error("rayskeleton: Hole in polygon is not simple."); | |
| 99 | // } | |
| 100 | 2x | poly.add_hole(new_hole); |
| 101 | } | |
| 102 | } | |
| 103 | // auto trait = PolygonSet::Traits_2(); | |
| 104 | // Traits_2 trait_val; | |
| 105 | // if(!is_closed_polygon_with_holes(poly, trait_val)) { | |
| 106 | // throw std::runtime_error("rayskeleton: Isn't closed polygon with holes."); | |
| 107 | // } | |
| 108 | // | |
| 109 | // if(!has_valid_orientation_polygon_with_holes(poly, trait_val)) { | |
| 110 | // throw std::runtime_error("rayskeleton: Polygon doesn't have valid orientation."); | |
| 111 | // } | |
| 112 | // if(!are_holes_and_boundary_pairwise_disjoint(poly, trait_val)) { | |
| 113 | // throw std::runtime_error("rayskeleton: Holes either intersect themselves or intersect with the outer boundary."); | |
| 114 | // } | |
| 115 | ||
| 116 | 139x | SsPtr ss; |
| 117 | try { | |
| 118 | 139x | ss = CGAL::create_interior_straight_skeleton_2(poly); |
| 119 | ! | } catch (...) { |
| 120 | ! | throw std::runtime_error("unknown cgal error occurred"); |
| 121 | }; | |
| 122 | // double lOffset = offset ; | |
| 123 | ||
| 124 | // int contours = 0; | |
| 125 | 139x | int bisectors = 0; |
| 126 | ||
| 127 | ||
| 128 | 43141x | for (Halfedge_const_iterator i = ss->halfedges_begin(); i != ss->halfedges_end(); ++i ) { |
| 129 | 43002x | if(!i->is_border()) { |
| 130 | 35696x | bisectors++; |
| 131 | } | |
| 132 | } | |
| 133 | 139x | List bisector_list(bisectors); |
| 134 | 139x | int bis_cntr = 0; |
| 135 | ||
| 136 | 43141x | for (Halfedge_const_iterator i = ss->halfedges_begin(); i != ss->halfedges_end(); ++i ) { |
| 137 | 43002x | if(!i->is_border()) { |
| 138 | NumericVector temp = Rcpp::NumericVector::create( | |
| 139 | 35696x | i->vertex()->point().x(), |
| 140 | 35696x | i->vertex()->point().y(), |
| 141 | 35696x | i->opposite()->vertex()->point().x(), |
| 142 | 35696x | i->opposite()->vertex()->point().y(), |
| 143 | 35696x | i->vertex()->time(), |
| 144 | 35696x | i->opposite()->vertex()->time(), |
| 145 | 35696x | i->vertex()->id(), |
| 146 | 35696x | i->opposite()->vertex()->id() |
| 147 | ); | |
| 148 | 35696x | bisector_list(bis_cntr) = temp; |
| 149 | 35696x | bis_cntr++; |
| 150 | } | |
| 151 | } | |
| 152 | ||
| 153 | 139x | List all_data = List::create(_["bisectors"] = bisector_list); |
| 154 | 139x | return(all_data); |
| 155 | } |